ios - Changing Size Classes in Code (Swift) -
i’ve been trying , running building adaptive layouts in pure code (no storyboards used). use layout anchors set constraints , utilize traitcollectiondidchange method vary between various sets of constraints , other interface changes. use switch statement call corresponding method corresponding set of constraints.
override func traitcollectiondidchange(_ previoustraitcollection: uitraitcollection?) { super.traitcollectiondidchange(previoustraitcollection) switch (traitcollection.horizontalsizeclass, traitcollection.verticalsizeclass) { case (.regular, .regular): setupregularregular() case (.compact, .compact): setupcompactcompact() case (.regular, .compact): setupregularcompact() case (.compact, .regular): setupcompactregular() default: break } }
for sake of testing, changed 1 constraint, centeryanchor.constraint. in portrait constant -150, in landscape want changed 50. ipad, set constant 0.
biglabel.centeryanchor.constraint(equalto: view.centeryanchor, constant: -150).isactive = true
it works fine when switching between iphone , ipad. however, if start rotating iphone portrait landscape, layout system fails, saying:
[layoutconstraints] unable simultaneously satisfy constraints. @ least 1 of constraints in following list 1 don't want. try this: (1) @ each constraint , try figure out don't expect; (2) find code added unwanted constraint or constraints , fix it. ( "<nslayoutconstraint:0x600000097890 uilabel:0x7fac02c08aa0'main label'.centery == uiview:0x7fac02e0a950.centery - 150 (active)>", "<nslayoutconstraint:0x604000097840 uilabel:0x7fac02c08aa0'main label'.centery == uiview:0x7fac02e0a950.centery + 50 (active)>" ) attempt recover breaking constraint <nslayoutconstraint:0x604000097840 uilabel:0x7fac02c08aa0'main label'.centery == uiview:0x7fac02e0a950.centery + 50 (active)>
i tried overriding various methods , setting isactive property of constraint false , true, didn’t help. searched web couple of days. no solution far. question is, how switch between size classes right way when rotating device? necessary override other method or something? there better solution adaptive layout in pure code? there best practices when comes adaptive layouts / size classes / layout anchors , constraints in code (without using storyboard)? help!
p.s. methods setting constraints are:
func setupcompactregular() { biglabel.centeryanchor.constraint(equalto: view.centeryanchor, constant: -150).isactive = true } func setupregularcompact() { biglabel.centeryanchor.constraint(equalto: view.centeryanchor, constant: 50).isactive = true }
the issue creating new constraints.. try holding reference constraint , change methods update them
func setupcompactregular() { self.biglabelcenteryanchor.constant = -150 } func setupregularcompact() { self.biglabelcenteryanchor.constant = 50 }
call layoutifneeded()
right after if doesnt update automatically
Comments
Post a Comment