Showing posts with label nslayoutconstraint. Show all posts
Showing posts with label nslayoutconstraint. Show all posts

Tuesday, August 21, 2018

Auto Layout constraint breaks when set active

Leave a Comment

I have a set of AL constraints positioning a child vc that has two positions, expanded and collapsed.

I found that when I add the collapsed constraint, a top anchor to bottom anchor constraint with a constant, when the vc is first created, there seems to be additional spacing when I activate it. Seemingly because the actual height isn't available at the time.

When I add the constraint in viewDidLayoutSubviews there additional spacing is gone and the constraint behaves properly. Except the issue that now when I switch between the constraints in an animation, I cannot deactivate the collapsed constraint as I switch to the expanded constraint and the constraint breaks. Possibly because viewDidLayoutSubviews is called throughout the transition animation.

Here's an abstract of vc setup.

var foregroundExpandedConstraint: NSLayoutConstraint! var foregroundCollapsedConstraint: NSLayoutConstraint!  var foregroundViewController: UIViewController? {     didSet {          setupforegroundViewController(foregroundViewController: foregroundViewController!)     } }  func setupforegroundViewController(foregroundViewController: UIViewController) {      addChildViewController(foregroundViewController)     foregroundViewController.didMove(toParentViewController: self)      guard let foregroundView = foregroundViewController.view else { return }     foregroundView.translatesAutoresizingMaskIntoConstraints = false     view.addSubview(foregroundView)      foregroundExpandedConstraint = foregroundView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 15)      let height =  view.safeAreaLayoutGuide.layoutFrame.height - 50 - 15     let cellHeight = ((height) / 6)             foregroundCollapsedConstraint = NSLayoutConstraint(item: foregroundView, attribute: .top, relatedBy: .equal, toItem: view.safeAreaLayoutGuide, attribute: .bottom, multiplier: 1, constant: (-cellHeight) * 2 - 50)      let foregroundViewControllerViewConstraints = [         foregroundView.leadingAnchor.constraint(equalTo: view.leadingAnchor),         foregroundView.trailingAnchor.constraint(equalTo: view.trailingAnchor),         foregroundView.heightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.heightAnchor, constant: -50 - 15),         foregroundExpandedConstraint!         ]       NSLayoutConstraint.activate(foregroundViewControllerViewConstraints) } 

And here the animations are preformed using UIViewPropertyAnimator.

func animateTransitionIfNeeded(state: ForegroundState, duration: TimeInterval) {      let containerFrameAnimator = UIViewPropertyAnimator(duration: duration, dampingRatio: 1) {         [unowned self] in          switch state {         case .expanded:             self.foregroundCollapsedConstraint?.isActive = false             self.foregroundExpandedConstraint?.isActive = true             self.view.layoutIfNeeded()         case .collapsed:             self.foregroundExpandedConstraint?.isActive = false             self.foregroundCollapsedConstraint?.isActive = true             self.view.layoutIfNeeded()         }     }      containerFrameAnimator.addCompletion {  [weak self] (position) in          if position == .start {             switch state {             case .collapsed:                 self?.foregroundCollapsedConstraint?.isActive = false                 self?.foregroundExpandedConstraint?.isActive = true                 self?.foregroundIsExpanded = true                 self?.view.layoutIfNeeded()             case .expanded:                 self?.foregroundExpandedConstraint?.isActive = false                 self?.foregroundCollapsedConstraint?.isActive = true                 self?.foregroundIsExpanded = false                 self?.view.layoutIfNeeded()             }         } else if position == .end {             switch state {             case .collapsed:                 self?.foregroundExpandedConstraint?.isActive = false                 self?.foregroundCollapsedConstraint?.isActive = true                 self?.foregroundIsExpanded = false             case .expanded:                 self?.foregroundExpandedConstraint?.isActive = false                 self?.foregroundCollapsedConstraint?.isActive = true                 self?.foregroundIsExpanded = true             }         }         self?.runningAnimations.removeAll()     } 

Again to reiterate, when I use the following code, setting the constraint as the vc is added to the view hierarchy, it doesn't layout properly. Checking the constraints I see they change after view did layout subviews is called. Each constraint changes appropriately except for the collapsed constraint.

When I add the collapsed constraint in view did layout subviews it behaves properly however I am unable to deactivate it going forwards and the constraint breaks.

override func viewDidLayoutSubviews() {     super.viewDidLayoutSubviews()      let height =  view.safeAreaLayoutGuide.layoutFrame.height - 50 - 15     let cellHeight = ((height) / 6)      if let v = foregroundViewController?.view {         foregroundCollapsedConstraint = NSLayoutConstraint(item: v, attribute: .top, relatedBy: .equal, toItem: view.safeAreaLayoutGuide, attribute: .bottom, multiplier: 1, constant: (-cellHeight) * 2 - 50)     } } 

Edit: I've created a repo demonstrating the issue: https://github.com/louiss98/UIViewPropertyAnimator-Layout-Test

Any suggestions?

1 Answers

Answers 1

You can eliminate the "broken" constraint by changing the constant instead of creating a new constraint.

In your viewDidLayoutSubviews() func,

change:

override func viewDidLayoutSubviews() {     super.viewDidLayoutSubviews()      let height =  view.safeAreaLayoutGuide.layoutFrame.height - 50 - 15     let cellHeight = ((height) / 6)      foregroundCollapsedConstraint = NSLayoutConstraint(item: testViewController.view, attribute: .top, relatedBy: .equal, toItem: view.safeAreaLayoutGuide, attribute: .bottom, multiplier: 1, constant: (-cellHeight) * 2 - 50) } 

to:

override func viewDidLayoutSubviews() {     super.viewDidLayoutSubviews()      let height =  view.safeAreaLayoutGuide.layoutFrame.height - 50 - 15     let cellHeight = ((height) / 6)      foregroundCollapsedConstraint.constant = (-cellHeight) * 2 - 50 } 
Read More

Tuesday, December 26, 2017

Why calling setNeedsUpdateConstraints isn't needed for constraint changes or animations?

Leave a Comment

Readings:

From this answer:

This is what the accepted answer suggests to animate your view changes:

_addBannerDistanceFromBottomConstraint.constant = 0  UIView.animate(withDuration: 5) {     self.view.layoutIfNeeded() } 

Why do we call layoutIfNeeded when we aren't changing the frames. We are changing the constraints, so (according to this other answer) shouldn't we instead be calling setNeedsUpdateConstraints?

Similarly this this highly viewed answer says:

If something changes later on that invalidates one of your constraints, you should remove the constraint immediately and call setNeedsUpdateConstraints

Observations:

I actually did try using them both. Using setNeedsLayout my view animates correctly to the left

import UIKit  class ViewController: UIViewController {      override func viewDidLoad() {         super.viewDidLoad()     }      @IBAction func animate(_ sender: UIButton) {          UIView.animate(withDuration: 1.8, animations: {             self.centerXConstraint.isActive = !self.centerXConstraint.isActive             self.view.setNeedsLayout()             self.view.layoutIfNeeded()         })     }      @IBOutlet weak var centerYConstraint: NSLayoutConstraint!     @IBOutlet var centerXConstraint: NSLayoutConstraint! } 

However using setNeedsUpdateConstraints doesn't animate, It just moves the view rapidly to the left.

import UIKit  class ViewController: UIViewController {      override func viewDidLoad() {         super.viewDidLoad()     }      @IBAction func animate(_ sender: UIButton) {          UIView.animate(withDuration: 1.8, animations: {         self.centerXConstraint.isActive = !self.centerXConstraint.isActive             self.view.setNeedsUpdateConstraints()             self.view.updateConstraintsIfNeeded()             })     }              @IBOutlet weak var centerYConstraint: NSLayoutConstraint!     @IBOutlet var centerXConstraint: NSLayoutConstraint! } 

If I don't want animation then using either of view.setNeedsLayout or view.setNeedsUpdateConstraints move it to the left. However:

  • with view.setNeedsLayout, after my button is tapped, my viewDidLayoutSubviews breakpoint is reached. But the updateViewConstraints breakpoint is never reached. This leaves me baffled as to how the constraints are getting updated...
  • with view.setNeedsUpdateConstraints, after the button is tapped my updateViewConstraints breakpoint is reached and then the viewDidLayoutSubviews breakpoint is reached. This does make sense, the constraints are updated, then the layoutSubviews is called.

Questions:

Based on my readings: if you change constraints then for it to become effective you MUST call setNeedsUpdateConstraints, but based on my observations that's wrong. Having the following code was enough to animate:

self.view.setNeedsLayout() self.view.layoutIfNeeded() 

WHY?

Then I thought maybe somehow under the hoods it's updating the constraints through other means. So I placed a breakpoint at override func updateViewConstraints and override func viewDidLayoutSubviews but only the viewDidLayoutSubviews reached its breakpoint.

So how is the Auto Layout engine managing this?

4 Answers

Answers 1

setNeedsUpdateConstraints will update the constraints that will be changed based on a change you have made. For example if your view has a neighboring view with which there a constraint of horizontal distance, and that neighbor view got removed, the constraint is invalid now. In this case you should remove that constraint and call setNeedsUpdateConstraints. It basically makes sure that all your constraints are valid. This will not redraw the view. You can read more about it here.
setNeedsLayout on the other hand marks the view for redrawing and putting it inside animation block makes the drawing animated.

Answers 2

A Playground

AutoLayout Playground with a button and a view. Any time you're suffering start with a Playground!

This is wrong

For starters... what is the view's horizontal position once the X constraint is disabled? You've left it ambiguous. Check out my Playground and how I animate from the left-side to the centre such that you can just keep tapping the button and play bounce the view. Reading the coverage of updating constraints and layouts it only makes sense to me to perform the animation in the layout phase.

@IBAction func animate(_ sender: UIButton) {      UIView.animate(withDuration: 1.8, animations: {         self.centerXConstraint.isActive = !self.centerXConstraint.isActive         self.view.setNeedsLayout()         self.view.layoutIfNeeded()     }) } 

This is also wrong

@IBAction func animate(_ sender: UIButton) {      UIView.animate(withDuration: 1.8, animations: {     self.centerXConstraint.isActive = !self.centerXConstraint.isActive         self.view.setNeedsUpdateConstraints()         self.view.updateConstraintsIfNeeded()         }) }     

In essence you're saying, set up this animation by suggesting you do it and then you force it. So there is no need for both.

`setNeeds...()` - is a suggestion  `...IfNeeded()` - is an imperative (AKA Now!) 

Here you seem my formulation. In the layout pass establish the Starting layout before the animation block and the ending layout in the block. Then iOS will correctly animate between the two points. Note - I don't leave any ambiguity along the horizontal axis.

@objc func animate(sender: AnyObject) {     guard let innerView = self.innerView,         let innerViewLeadingConstraint = self.innerViewLeadingConstraint,         let innerViewCenterXConstraint = self.innerViewCenterXConstraint else {         return     }      self.view.layoutIfNeeded()     UIView.animate(withDuration: 1.8, animations: {         if self.view.constraints.contains(innerViewCenterXConstraint) {             self.view.removeConstraint(innerViewCenterXConstraint)             self.view.addConstraint(innerViewLeadingConstraint)         } else {             self.view.removeConstraint(innerViewLeadingConstraint)             self.view.addConstraint(innerViewCenterXConstraint)         }         self.view.layoutIfNeeded()     }) } 

As described at ObjC.io

The first step – updating constraints – can be considered a “measurement pass.” It happens bottom-up (from subview to super view) and prepares the information needed for the layout pass to actually set the views’ frame. You can trigger this pass by calling setNeedsUpdateConstraints. Any changes you make to the system of constraints itself will automatically trigger this. However, it is useful to notify Auto Layout about changes in custom views that could affect the layout. Speaking of custom views, you can override updateConstraints to add the local constraints needed for your view in this phase.

The second step – layout – happens top-down (from super view to subview). This layout pass actually applies the solution of the constraint system to the views by setting their frames (on OS X) or their center and bounds (on iOS). You can trigger this pass by calling setNeedsLayout, which does not actually go ahead and apply the layout immediately, but takes note of your request for later. This way you don’t have to worry about calling it too often, since all the layout requests will be coalesced into one layout pass. To force the system to update the layout of a view tree immediately, you can call layoutIfNeeded/layoutSubtreeIfNeeded (on iOS and OS X respectively). This can be helpful if your next steps rely on the views’ frame being up to date. In your custom views you can override layoutSubviews/layout to gain full control over the layout pass. We will show use cases for this later on.

Autolayout Guide

This further clarifies the rules of AutoLayout when changing size.

Instead of immediately updating the affected views’ frames, Auto Layout schedules a layout pass for the near future. This deferred pass updates the layout’s constraints and then calculates the frames for all the views in the view hierarchy.

You can schedule your own deferred layout pass by calling the setNeedsLayout method or the setNeedsUpdateConstraints method.

The deferred layout pass actually involves two passes through the view hierarchy:

  • The update pass updates the constraints, as necessary
  • The layout pass repositions the view’s frames, as necessary

Mysteries of Auto-Layout

There are a pair of 2015 WWDC talks you should watch.

Answers 3

This is a common misunderstanding among iOS developers.

Here's one of my "golden rules" for Auto Layout:

Don't bother about "updating constraints".

You never need to call any of these methods:

  • setNeedsUpdateConstraints()
  • updateConstraintsIfNeeded()
  • updateConstraints()
  • updateViewConstraints()

except for the very rare case that you have a tremendously complex layout which slows down your app (or you deliberately choose to implement layout changes in an atypical way).

The Preferred Way to Change Your Layout

Normally, when you want to change your layout, you would activate / deactivate or change layout constraints directly after a button tap or whichever event triggered the change, e.g. in a button's action method:

@IBAction func toggleLayoutButtonTapped(_ button: UIButton) {     toggleLayout() }  func toggleLayout() {     isCenteredLayout = !isCenteredLayout      if isCenteredLayout {         centerXConstraint.isActive = true      } else {         centerXConstraint.isActive = false     } } 

As Apple puts it in their Auto Layout Guide:

It is almost always cleaner and easier to update a constraint immediately after the affecting change has occurred. Deferring these changes to a later method makes the code more complex and harder to understand.

You can of course also wrap this constraint change in an animation: You first perform the constraint change and then animate the changes by calling layoutIfNeeded() in the animation closure:

@IBAction func toggleLayoutButtonTapped(_ button: UIButton) {     // 1. Perform constraint changes:     toggleLayout()     // 2. Animate the changes:     UIView.animate(withDuration: 1.8, animations: {         view.layoutIfNeeded()     } } 

Whenever you change a constraint, the system automatically schedules a deferred layout pass, which means that the system will recompute the layout in the near future. No need to call setNeedsUpdateConstraints() because you just did update (change) the constraint yourself! What needs to be updated is the layout i.e. the frames of all your views, not any other constraint.

The Principle of Invalidation

As previously stated, the iOS layout system usually doesn't react immediately to constraint changes but only schedules a deferred layout pass. That's for performance reasons. Think of it like this:

When you go shopping groceries, you put an item in your cart but you don't pay it immediately. Instead, you put other items in your cart until you feel like you got everything you need. Only then you proceed to the cashier and pay all your groceries at once. It's way more efficient.

Due to this deferred layout pass there is a special mechanism needed to handle layout changes. I call it The Princpile of Invalidation. It's a 2-step mechanism:

  1. You mark something as invalid.
  2. If something is invalid, you perform some action to make it valid again.

In terms of the layout engine this corresponds to:

  1. setNeedsLayout()
  2. layoutIfNeeded()

and

  1. setNeedsUpdateConstraints()
  2. updateConstraintsIfNeeded()

The first pair of methods will result in an immediate (not deferred) layout pass: First you invalidate the layout and then you recompute the layout immediately if it's invalid (which it is, of course).

Usually you don't bother if the layout pass will happen now or a couple of milliseconds later so you normally only call setNeedsLayout() to invalidate the layout and then wait for the deferred layout pass. This gives you the opportunity to perform other changes to your constraints and then update the layout slightly later but all at once (→ shopping cart).

You only need to call layoutIfNeeded() when you need the layout to be recomputed right now. That might be the case when you need to perform some other calculations based on the resulting frames of your new layout.

The second pair of methods will result in an immediate call of updateConstraints() (on a view or updateViewConstraints() on a view controller). But that's something you normally shouldn't do.

Changing Your Layout in a Batch

Only when your layout is really slow and your UI feels laggy due to your layout changes you can choose a different approach that the one stated above: Rather than updating a constraint directly in response to a button tap you just make a "note" of what you want to change and another "note" that your constraints need to be updated.

@IBAction func toggleLayoutButtonTapped(_ button: UIButton) {     // 1. Make a note how you want your layout to change:     isCenteredLayout = !isCenteredLayout     // 2. Make a note that your constraints need to be updated (invalidate constraints):     setNeedsUpdateConstraints() } 

This schedules a deferred layout pass and ensures that updateConstraints() / updateViewConstraints() will be called during the layout pass. So you may now even perform other changes and call setNeedsUpdateConstraints() a thousand times – your constraints will still only be updated once during the next layout pass.

Now you override updateConstraints() / updateViewConstraints() and perform the necessary constraint changes based on your current layout state (i.e. what you have "noted" above in "1."):

override func updateConstraints() {     if isCenteredLayout {         centerXConstraint.isActive = true      } else {         centerXConstraint.isActive = false     }      super.updateConstraints() } 

Again, this is only your last resort if the layout is really slow and you're dealing will hundreds or thousands of constraints. I have never needed to use updateConstraints() in any of my projects, yet.

I hope this make things a little clearer.

Additional resources:

Answers 4

I will try to explain it simply:

The first thing to remember is that updating constraints does cause the layout of views to be updated immediately. This is for performance reasons as laying everything out can take time so it 'makes note' of changes that need to take place then does a single layout pass.

Taking that one step further you can then not even update constraints when something affecting them changes but just flag that the constraints need to be updated. Even updating the constraints themselves (without laying out the views) can take time and the same ones could change both ways (i.e. active and inactive).

Now considering all that what setNeedsUpdateConstraints() does is to flag that the constraints for a view need to be re-calculated BEFORE the next layout pass because something about them has changed it doesn't make any constraint changes of affect the current layout at all. Then you should implement your own version of the updateConstraints() method to actually make the required changes to the constraints based on the current app state, etc.

So when the system decides the next layout pass should occur anything that has had setNeedsUpdateConstraints() called on it (or the system decides needs updating) will get its implementation of updateConstraints() called to make those changes. This will happen automatically before the laying out is done.

Now the setNeedsLayout() and layoutIfNeeded() are similar but for control of the actual layout processing itself.

When something that affects the layout of a view changes you can call setNeedsLayout() so that that view is 'flagged' to have it's layout re-calculated during the next layout pass. So if you change constraints directly (instead of perhaps using setNeedsUpdateConstraints() and updateConstraints()) you can then call setNeedsLayout() to indicate that the views layout has changed and will need to be re-calculated during the next layout pass.

What layoutIfNeeded() does is to force the layout pass to happen then and there rather than waiting for when the system determines it should next happen. It's that the forces the re-calculation of the layouts of views based on the current sate of everything. Note also that when you do this fist anything that has been flagged with setNeedsUpdateConstraints() will first call it's updateConstraints() implementation.

So no layout changes are made until the system decides to do a layout pass or your app calls layoutIfNeeded().

In practice you rarely need to use setNeedsUpdateConstraints() and implement your own version of updateConstraints() unless something is really complex and you can get by with updating view constraints directly and using setNeedsLayout() and layoutIfNeeded().

So in summary setNeedsUpdateConstraints doesn't need to be called to make constraint changes take affect and in fact if you change constraints they will automatically take affect when the system decides it's time for a layout pass.

When animating you want slightly more control over what is happening because you don't want an immediate change of the layout but to see it change over time. So for simplicity let's say you have an animation that takes a second (a view moves from the left of the screen to the right) you update the constraint to make the view move from left to right but if that was all you did it would just jump from one place to another when the system decided it was time for a layout pass. So instead you do something like the following (assuming testView is a sub view of self.view):

testView.leftPositionConstraint.isActive = false // always de-activate testView.rightPositionConstraint.isActive = true // before activation UIView.animate(withDuration: 1) {     self.view.layoutIfNeeded() } 

Let's break that down:

First this testView.leftPositionConstraint.isActive = false turns off the constraint keeping the view in the left hand position but the layout of the view is not yet adjusted.

Second this testView.rightPositionConstraint.isActive = true turns on the constraint keeping the view in the right hand position but again the layout of the view is not yet adjusted.

Then you schedule the animation and say that during each 'time slice' of that animation call self.view.layoutIfNeeded(). So what that will do is force a layout pass for self.view every time the animation updates causing the testView layout to be re-calculated based on it's position through the animation i.e. after 50% of the animation the layout will be 50% between the stating (current) layout and the required new layout.

Thus doing that the animation takes affect.

So in overall summary:

setNeedsConstraint() - called to inform the system that the constraints of a view will need to be updated because something affecting them has changed. The constraints are not actually updated until the system decides a layout pass is needed or the user forces one.

updateConstraints() - this should be implemented for views to update the constraints based on the apps state.

setNeedsLayout() - this informs the system that something affecting the layout of a view (constraints probably) have changed and the layout will need to be re-calculated during the next layout pass. Nothing happens to the layout at that time.

layoutIfNeeded() - performs a layout pass for the view now rather than waiting for the next system scheduled one. At this point the view and it's sub views layouts will actually be re-calculated.

Read More

Saturday, November 11, 2017

How to “find” your own constraint?

Leave a Comment

Say I have a UIView,

 class CleverView: UIView 

In the custom class, I want to do this:

func changeWidth() {    let c = ... find my own layout constraint, for "width"   c.constant = 70 * Gameinfo.ImportanceOfEnemyFactor } 

Similarly I wanna be able to "find" like that, the constraint (or I guess, all constraints, there could be more than one) attached to one of the four edges.

So, to look through all the constraints attached to me, and find any width/height ones, or indeed any relevant to a given (say, "left") edge.

Any ideas?


Please, note that (obviously) I am asking how to do this dynamically/programmatically.

(Yes, you can say "link to the constraint" or "use an ID" - the whole point of the QA is how to find them on the fly and work dynamically.)

3 Answers

Answers 1

There are really two cases:

  1. Constraints regarding a view's size or relations to descendant views are saved in itself
  2. Constraints between two views are saved in the views' lowest common ancestor

Thus, we need to check the view itself and all its superviews for constraints. One approach could be:

extension UIView {      // retrieves all constraints that mention the view     func getAllConstraints() -> [NSLayoutConstraint] {          // array will contain self and all superviews         var views = [self]          // get all superviews         var view = self         while let superview = view.superview {             views.append(superview)             view = superview         }          // transform views to constraints and filter only those         // constraints that include the view itself         return views.flatMap({ $0.constraints }).filter { constraint in             return constraint.firstItem as? UIView == self ||                 constraint.secondItem as? UIView == self         }     } } 

You can apply all kinds of filters after getting all constraints about a view, and I guess that's the most difficult part. Some examples:

extension UIView {      // Example 1: Get all width constraints involving this view     // We could have multiple constraints involving width, e.g.:     // - two different width constraints with the exact same value     // - this view's width equal to another view's width     // - another view's height equal to this view's width (this view mentioned 2nd)     func getWidthConstraints() -> [NSLayoutConstraint] {         return getAllConstraints().filter( {             ($0.firstAttribute == .width && $0.firstItem as? UIView == self) ||             ($0.secondAttribute == .width && $0.secondItem as? UIView == self)         } )     }      // Example 2: Change width constraint(s) of this view to a specific value     // Make sure that we are looking at an equality constraint (not inequality)     // and that the constraint is not against another view     func changeWidth(to value: CGFloat) {          getAllConstraints().filter( {             $0.firstAttribute == .width &&                 $0.relation == .equal &&                 $0.secondAttribute == .notAnAttribute         } ).forEach( {$0.constant = value })     }      // Example 3: Change leading constraints only where this view is     // mentioned first. We could also filter leadingMargin, left, or leftMargin     func changeLeading(to value: CGFloat) {         getAllConstraints().filter( {             $0.firstAttribute == .leading &&                 $0.firstItem as? UIView == self         }).forEach({$0.constant = value})     } } 

// edit: Enhanced examples and clarified their explanations in comments

Answers 2

I guess you can work with constraints property of UIView. constraints basically returns an array of constraint directly assigned to UIView. It will not be able to get you the constraints held by superview such as leading, trailing, top or bottom but width and height constraints are held by View itself. For superview's constraints, you can loop through superview's constraints. Lets say the clever view has these constraints:

enter image description here

class CleverView: UIView {      func printSuperViewConstriantsCount() {         var c = 0         self.superview?.constraints.forEach({ (constraint) in             guard constraint.secondItem is CleverView || constraint.firstItem is CleverView else {                 return             }             c += 1             print(constraint.firstAttribute.toString())         })         print("superview constraints:\(c)")     }      func printSelfConstriantsCount() {         self.constraints.forEach { (constraint) in             return print(constraint.firstAttribute.toString())         }         print("self constraints:\(self.constraints.count)")     } } 

Output:

top
leading
trailing
superview constraints:3
height
self constraints:1

Basically, you can look at NSLayoutConstraint class to get the info out about a particular constraint.

To print the name of constraints, we can use this extension

extension NSLayoutAttribute {     func toString() -> String {         switch self {         case .left:             return "left"         case .right:             return "right"         case .top:             return "top"         case .bottom:             return "bottom"         case .leading:             return "leading"         case .trailing:             return "trailing"         case .width:             return "width"         case .height:             return "height"         case .centerX:             return "centerX"         case .centerY:             return "centerY"         case .lastBaseline:             return "lastBaseline"         case .firstBaseline:             return "firstBaseline"         case .leftMargin:             return "leftMargin"         case .rightMargin:             return "rightMargin"         case .topMargin:             return "topMargin"         case .bottomMargin:             return "bottomMargin"         case .leadingMargin:             return "leadingMargin"         case .trailingMargin:             return "trailingMargin"         case .centerXWithinMargins:             return "centerXWithinMargins"         case .centerYWithinMargins:             return "centerYWithinMargins"         case .notAnAttribute:             return "notAnAttribute"         }     } } 

Answers 3

I use the following extension to examine all constraints:

extension NSLayoutConstraint {     class func listConstraints (_ v:UIView?) {         var v = v         if v == nil {             v = UIApplication.shared.keyWindow         }         for vv in v!.subviews {             let arr1 = vv.constraintsAffectingLayout(for:.horizontal)             let arr2 = vv.constraintsAffectingLayout(for:.vertical)             NSLog("\n\n%@\nH: %@\nV:%@", vv, arr1, arr2);             if vv.subviews.count > 0 {                 self.listConstraints(vv)             }         }     } } 

Just call that with NSLayoutConstraint.listConstraints(nil) or NSLayoutConstraint.listConstraints(myView). That lists all constraints, each one telling all details about itself, so it's pretty easy to figure out which one is causing any particular phenomenon. Instead of the NSLog, you can easily add some sort of code to do something else.

Read More

Tuesday, January 3, 2017

Programmatic auto-layout, constraints in SWTableViewCell

Leave a Comment

I'm trying to add a detail view to SWTableViewCell.

The constraints are tied to all elements of the cell, and I'm trying to get a detailed view to animate from the table view cell.

Photo of what is now versus what is desired:

constraints change size of the cell, when it's desired to have a subview only be resized

I've been spending a lot of time experimenting blindly, and trying to do a deep dive in manual auto-layout. I haven't been able to identify how to get the desired result. I attempted to transfer all the contents to another subview, however, removing elements from self did not solve this.

Code with the constraints:

- (void)initializer { layoutUpdating = NO; // Set up scroll view that will host our cell content self.cellScrollView = [[SWCellScrollView alloc] init]; self.cellScrollView.translatesAutoresizingMaskIntoConstraints = NO; self.cellScrollView.delegate = self; self.cellScrollView.showsHorizontalScrollIndicator = NO; self.cellScrollView.scrollsToTop = NO; self.cellScrollView.scrollEnabled = YES;  _contentCellView = [[UIView alloc] init]; [self.cellScrollView addSubview:_contentCellView];  // Add the cell scroll view to the cell UIView *contentViewParent = self; UIView *clipViewParent = self.cellScrollView; if (![NSStringFromClass([[self.subviews objectAtIndex:0] class]) isEqualToString:kTableViewCellContentView]) {     // iOS 7     contentViewParent = [self.subviews objectAtIndex:0];     clipViewParent = self; } NSArray *cellSubviews = [contentViewParent subviews]; [self insertSubview:self.cellScrollView atIndex:0]; for (UIView *subview in cellSubviews) {     [_contentCellView addSubview:subview]; }  // Set scroll view to perpetually have same frame as self. Specifying relative to superview doesn't work, since the latter UITableViewCellScrollView has different behaviour. [self addConstraints:@[                        [NSLayoutConstraint constraintWithItem:self.cellScrollView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0],                        [NSLayoutConstraint constraintWithItem:self.cellScrollView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.0],                        [NSLayoutConstraint constraintWithItem:self.cellScrollView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0.0],                        [NSLayoutConstraint constraintWithItem:self.cellScrollView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeRight multiplier:1.0 constant:0.0],                        ]];  self.tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(scrollViewTapped:)]; self.tapGestureRecognizer.cancelsTouchesInView = NO; self.tapGestureRecognizer.delegate             = self; [self.cellScrollView addGestureRecognizer:self.tapGestureRecognizer];  self.longPressGestureRecognizer = [[SWLongPressGestureRecognizer alloc] initWithTarget:self action:@selector(scrollViewPressed:)]; self.longPressGestureRecognizer.cancelsTouchesInView = NO; self.longPressGestureRecognizer.minimumPressDuration = kLongPressMinimumDuration; self.longPressGestureRecognizer.delegate = self; [self.cellScrollView addGestureRecognizer:self.longPressGestureRecognizer];  // Create the left and right utility button views, as well as vanilla UIViews in which to embed them.  We can manipulate the latter in order to effect clipping according to scroll position. // Such an approach is necessary in order for the utility views to sit on top to get taps, as well as allow the backgroundColor (and private UITableViewCellBackgroundView) to work properly.  self.leftUtilityClipView = [[UIView alloc] init]; self.leftUtilityClipConstraint = [NSLayoutConstraint constraintWithItem:self.leftUtilityClipView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0.0]; self.leftUtilityButtonsView = [[SWUtilityButtonView alloc] initWithUtilityButtons:nil                                                                        parentCell:self                                                             utilityButtonSelector:@selector(leftUtilityButtonHandler:)];  self.rightUtilityClipView = [[UIView alloc] initWithFrame:self.bounds]; self.rightUtilityClipConstraint = [NSLayoutConstraint constraintWithItem:self.rightUtilityClipView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeRight multiplier:1.0 constant:0.0]; self.rightUtilityButtonsView = [[SWUtilityButtonView alloc] initWithUtilityButtons:nil                                                                         parentCell:self                                                              utilityButtonSelector:@selector(rightUtilityButtonHandler:)];   UIView *clipViews[] = { self.rightUtilityClipView, self.leftUtilityClipView }; NSLayoutConstraint *clipConstraints[] = { self.rightUtilityClipConstraint, self.leftUtilityClipConstraint }; UIView *buttonViews[] = { self.rightUtilityButtonsView, self.leftUtilityButtonsView }; NSLayoutAttribute alignmentAttributes[] = { NSLayoutAttributeRight, NSLayoutAttributeLeft };  for (NSUInteger i = 0; i < 2; ++i) {     UIView *clipView = clipViews[i];     NSLayoutConstraint *clipConstraint = clipConstraints[i];     UIView *buttonView = buttonViews[i];     NSLayoutAttribute alignmentAttribute = alignmentAttributes[i];      clipConstraint.priority = UILayoutPriorityDefaultHigh;      clipView.translatesAutoresizingMaskIntoConstraints = NO;     clipView.clipsToBounds = YES;      [clipViewParent addSubview:clipView];     [self addConstraints:@[                            // Pin the clipping view to the appropriate outer edges of the cell.                            [NSLayoutConstraint constraintWithItem:clipView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0],                            [NSLayoutConstraint constraintWithItem:clipView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.0],                            [NSLayoutConstraint constraintWithItem:clipView attribute:alignmentAttribute relatedBy:NSLayoutRelationEqual toItem:self attribute:alignmentAttribute multiplier:1.0 constant:0.0],                            clipConstraint,                            ]];      [clipView addSubview:buttonView];     [self addConstraints:@[                            // Pin the button view to the appropriate outer edges of its clipping view.                            [NSLayoutConstraint constraintWithItem:buttonView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:clipView attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0],                            [NSLayoutConstraint constraintWithItem:buttonView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:clipView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.0],                            [NSLayoutConstraint constraintWithItem:buttonView attribute:alignmentAttribute relatedBy:NSLayoutRelationEqual toItem:clipView attribute:alignmentAttribute multiplier:1.0 constant:0.0],                             // Constrain the maximum button width so that at least a button's worth of contentView is left visible. (The button view will shrink accordingly.)                            [NSLayoutConstraint constraintWithItem:buttonView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationLessThanOrEqual toItem:self.contentView attribute:NSLayoutAttributeWidth multiplier:1.0 constant:-kUtilityButtonWidthDefault],                            ]]; }  self.utilityView = [[UIView alloc] initWithFrame: CGRectMake(0, self.bounds.size.height, self.bounds.size.width, 0)]; [self.utilityView setBackgroundColor: [UIColor darkGrayColor]]; [self addSubview: self.utilityView]; [self sendSubviewToBack: self.utilityView]; } 

The table view calls a public method within beginUpdates and endUpdates, and the animation is UIView animateWithDuration:.

The view hierarchy:

   <UIWindow: 0x7f85cfe11840; frame = (0 0; 414 736); gestureRecognizers = <NSArray: 0x608000242d60>; layer = <UIWindowLayer: 0x60800002c300>>   | <UIView: 0x7f85cff08bc0; frame = (0 0; 414 736); autoresize = W+H; layer = <CALayer: 0x618000027040>>   |    | <UIView: 0x7f85cfc03ce0; frame = (0 0; 414 66); layer = <CALayer: 0x60000002e4c0>>   |    |    | <LBHamburgerButton: 0x7f85cfc0cd20; baseClass = UIButton; frame = (314 10; 50 50); opaque = NO; layer = <CALayer: 0x60000002e620>>   |    |    |    | <CAShapeLayer: 0x60800022cce0> (layer)   |    |    |    | <CAShapeLayer: 0x60800022d840> (layer)   |    |    |    | <CAShapeLayer: 0x60800022d920> (layer)   |    | <UIView: 0x7f85cfc08e70; frame = (0 66; 414 670); layer = <CALayer: 0x60000002e5a0>>   |    |    | <UIView: 0x7f85cff16790; frame = (0 0; 414 736); autoresize = W+H; layer = <CALayer: 0x61800002c240>>   |    |    |    | <iCarousel: 0x7f85cff16930; frame = (0 10; 414 80); autoresize = W+H; layer = <CALayer: 0x61800002c260>>   |    |    |    |    | <UIView: 0x7f85cff16f10; frame = (0 0; 414 80); autoresize = W+H; gestureRecognizers = <NSArray: 0x618000241f80>; layer = <CALayer: 0x61800002c280>>   |    |    |    |    |    | <UIView: 0x7f85cfc13a70; frame = (108.998 -0.000800016; 196.004 80.0016); layer = <CALayer: 0x60000002fea0>>   |    |    |    |    |    |    | <UILabel: 0x7f85cff1ebb0; frame = (0 0; 196 80); userInteractionEnabled = NO; layer = <_UILabelLayer: 0x6180002819a0>>   |    |    |    |    |    | <UIView: 0x7f85cff24150; frame = (-125.656 -18.322; 225.889 116.644); userInteractionEnabled = NO; layer = <CALayer: 0x6180000279a0>>   |    |    |    |    |    |    | <UILabel: 0x7f85cfd1af40; frame = (0 0; 196 80); userInteractionEnabled = NO; layer = <_UILabelLayer: 0x610000488660>>   |    |    |    |    |    | <UIView: 0x7f85cfc1c280; frame = (313.767 -18.322; 225.889 116.644); userInteractionEnabled = NO; layer = <CALayer: 0x6000000309e0>>   |    |    |    |    |    |    | <UILabel: 0x7f85cfd1b1c0; frame = (0 0; 196 80); userInteractionEnabled = NO; layer = <_UILabelLayer: 0x610000489380>>   |    |    |    |    |    | <UIView: 0x7f85cfc19630; frame = (-444.013 -99.6275; 306.865 279.255); hidden = YES; userInteractionEnabled = NO; layer = <CALayer: 0x600000030540>>   |    |    |    |    |    |    | <UILabel: 0x7f85cfe29790; frame = (0 0; 196 80); userInteractionEnabled = NO; layer = <_UILabelLayer: 0x60800009aae0>>   |    |    |    | <UIView: 0x7f85cff17590; frame = (0 95; 414 60); layer = <CALayer: 0x61800002c3e0>>   |    |    |    |    | <UIButton: 0x7f85cff17730; frame = (0 0; 60 60); opaque = NO; layer = <CALayer: 0x61800002c440>>   |    |    |    |    | <UIButton: 0x7f85cff179f0; frame = (354 0; 60 60); opaque = NO; tag = 1; layer = <CALayer: 0x61800002c460>>   |    |    |    |    | <UILabel: 0x7f85cff17cb0; frame = (107 0; 200 60); userInteractionEnabled = NO; layer = <_UILabelLayer: 0x6180002873f0>>   |    |    |    | <UIView: 0x7f85cff189d0; frame = (0 158; 414 512); layer = <CALayer: 0x61800002c620>>   |    |    |    |    | <UITableView: 0x7f85d1842000; frame = (0 0; 414 512); clipsToBounds = YES; gestureRecognizers = <NSArray: 0x618000242c70>; layer = <CALayer: 0x61800002cba0>; contentOffset: {0, 0}; contentSize: {414, 8160.0099999997765}>   |    |    |    |    |    | <UITableViewWrapperView: 0x7f85d1845a00; frame = (0 0; 414 512); gestureRecognizers = <NSArray: 0x618000242fa0>; layer = <CALayer: 0x61800002cca0>; contentOffset: {0, 0}; contentSize: {414, 512}>   |    |    |    |    |    |    | <CurrentOrdersTableViewCell: 0x7f85d1821800; baseClass = UITableViewCell; frame = (0 640; 414 80); hidden = YES; autoresize = W; layer = <CALayer: 0x618000031400>>   |    |    |    |    |    |    |    | <UIView: 0x7f85cff23fb0; frame = (0 44; 320 0); layer = <CALayer: 0x618000032540>>   |    |    |    |    |    |    |    | <SWCellScrollView: 0x7f85d1876000; baseClass = UIScrollView; frame = (0 0; 414 80); clipsToBounds = YES; gestureRecognizers = <NSArray: 0x618000249450>; layer = <CALayer: 0x6180000314c0>; contentOffset: {90, 0}; contentSize: {594, 80}>   |    |    |    |    |    |    |    |    | <UIView: 0x7f85cff22ac0; frame = (90 0; 414 79.6667); layer = <CALayer: 0x6180000315c0>>   |    |    |    |    |    |    |    |    |    | <UITableViewCellContentView: 0x7f85cff224a0; frame = (0 0; 414 79.6667); gestureRecognizers = <NSArray: 0x618000249300>; layer = <CALayer: 0x618000031440>>   |    |    |    |    |    |    |    |    |    |    | <UILabel: 0x7f85cff25470; frame = (20 0; 66.8 12); userInteractionEnabled = NO; layer = <_UILabelLayer: 0x61800028aaf0>>   |    |    |    |    |    |    |    |    |    |    | <UILabel: 0x7f85cff256f0; frame = (96.8 0; 66.8 12); userInteractionEnabled = NO; layer = <_UILabelLayer: 0x61800028ab90>>   |    |    |    |    |    |    |    |    |    |    | <UILabel: 0x7f85cff25970; frame = (173.6 0; 66.8 12); userInteractionEnabled = NO; layer = <_UILabelLayer: 0x61800028ac30>>   |    |    |    |    |    |    |    |    |    |    | <UILabel: 0x7f85cff25bf0; frame = (250.4 0; 66.8 12); userInteractionEnabled = NO; layer = <_UILabelLayer: 0x61800028acd0>>   |    |    |    |    |    |    |    |    |    |    | <UILabel: 0x7f85cff25e70; frame = (327.2 0; 66.8 12); userInteractionEnabled = NO; layer = <_UILabelLayer: 0x61800028ad70>>   |    |    |    |    |    |    |    |    |    |    | <UILabel: 0x7f85cff260f0; frame = (20 15; 66.8 12); userInteractionEnabled = NO; layer = <_UILabelLayer: 0x61800028ae10>>   |    |    |    |    |    |    |    |    |    |    | <UILabel: 0x7f85cfe264a0; frame = (96.8 15; 66.8 12); userInteractionEnabled = NO; layer = <_UILabelLayer: 0x60800009ba30>>   |    |    |    |    |    |    |    |    |    |    | <UILabel: 0x7f85cfe26720; frame = (173.6 15; 66.8 12); userInteractionEnabled = NO; layer = <_UILabelLayer: 0x60800009bad0>>   |    |    |    |    |    |    |    |    |    |    | <UILabel: 0x7f85cfe269a0; frame = (250.4 15; 66.8 12); userInteractionEnabled = NO; layer = <_UILabelLayer: 0x60800009bb70>>   |    |    |    |    |    |    |    |    |    |    | <UILabel: 0x7f85cfe270e0; frame = (327.2 15; 66.8 12); userInteractionEnabled = NO; layer = <_UILabelLayer: 0x60800009bc10>>   |    |    |    |    |    |    |    |    | <UIView: 0x7f85cff23a10; frame = (504 0; 0 80); clipsToBounds = YES; hidden = YES; layer = <CALayer: 0x618000031c00>>   |    |    |    |    |    |    |    |    |    | <SWUtilityButtonView: 0x7f85cff23bb0; frame = (-90 0; 90 80); layer = <CALayer: 0x618000031c60>>   |    |    |    |    |    |    |    |    |    |    | <UIButton: 0x7f85cfe28a20; frame = (0 0; 90 80); opaque = NO; gestureRecognizers = <NSArray: 0x60800024c2d0>; layer = <CALayer: 0x608000234900>>   |    |    |    |    |    |    |    |    |    |    |    | <UIButtonLabel: 0x7f85cfe28ce0; frame = (11 29.3333; 68.3333 21.6667); opaque = NO; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x60800009c570>>   |    |    |    |    |    |    |    |    | <UIView: 0x7f85cff236b0; frame = (90 0; 0 80); clipsToBounds = YES; hidden = YES; layer = <CALayer: 0x618000031b40>>   |    |    |    |    |    |    |    |    |    | <SWUtilityButtonView: 0x7f85cff23850; frame = (0 0; 90 80); layer = <CALayer: 0x618000031ba0>>   |    |    |    |    |    |    |    |    |    |    | <UIButton: 0x7f85cfe27360; frame = (0 0; 90 80); opaque = NO; gestureRecognizers = <NSArray: 0x60800024aa70>; layer = <CALayer: 0x6080002334e0>>   |    |    |    |    |    |    |    |    |    |    |    | <UIButtonLabel: 0x7f85cfe27620; frame = (8.66667 29.3333; 73 21.6667); opaque = NO; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x60800009bd00>>   |    |    |    |    |    |    |    |    | <UIImageView: 0x7f85cfe290c0; frame = (498.667 3; 2.33333 74); alpha = 0; opaque = NO; autoresize = LM; userInteractionEnabled = NO; layer = <CALayer: 0x608000234f20>>   |    |    |    |    |    |    |    | <_UITableViewCellSeparatorView: 0x7f85cfe28680; frame = (0 79.6667; 414 0.333333); layer = <CALayer: 0x6080002347a0>>   |    |    |    |    |    |    |  

0 Answers

Read More

Sunday, September 4, 2016

Catch UIViewAlertForUnsatisfiableConstraints in production

Leave a Comment

Is it possible to catch autolayout constraint ambiguities in production – the equivalent of a UIViewAlertForUnsatisfiableConstraints breakpoint but for production apps?

My goal would be to add a global handler that would report such errors to a logging system.

2 Answers

Answers 1

The symbol UIViewAlertForUnsatisfiableConstraints actually is a function :

_UIViewAlertForUnsatisfiableConstraints(NSLayoutConstraint* unsatisfiableConstraint, NSArray<NSLayoutConstraint*>* allConstraints).

It is private, so you can't replace it.

But it is called from private method -[UIView engine:willBreakConstraint:dueToMutuallyExclusiveConstraints:], which can be swizzled. This method has approximately this content:

void -[UIView engine:willBreakConstraint:dueToMutuallyExclusiveConstraints:] {   if ([self _isUnsatisfiableConstraintsLoggingSuspended]) {     [self _recordConstraintBrokenWhileUnsatisfiableConstraintsLoggingSuspended:$arg4]; // add constraint to some pool   }   else {     if (__UIConstraintBasedLayoutVisualizeMutuallyExclusiveConstraints) {       // print something in os_log     }     else {       _UIViewAlertForUnsatisfiableConstraints($arg4, $arg5);     }   } } 

If I understand correctly from this article, __UIConstraintBasedLayoutVisualizeMutuallyExclusiveConstraints will always return NO on iOS, so all you need to do is to check private bool property called _isUnsatisfiableConstraintsLoggingSuspended and call original method then.

This is result code example:

#import <objc/runtime.h>  void SwizzleInstanceMethod(Class classToSwizzle, SEL origSEL, Class myClass, SEL newSEL) {   Method methodToSwizzle = class_getInstanceMethod(classToSwizzle, origSEL);   Method myMethod = class_getInstanceMethod(myClass, newSEL);   class_replaceMethod(classToSwizzle, newSEL, method_getImplementation(methodToSwizzle), method_getTypeEncoding(methodToSwizzle));   class_replaceMethod(classToSwizzle, origSEL, method_getImplementation(myMethod), method_getTypeEncoding(myMethod)); }  @interface InterceptUnsatisfiableConstraints : NSObject @end  @implementation InterceptUnsatisfiableConstraints  + (void)load {   static dispatch_once_t onceToken;   dispatch_once(&onceToken, ^{     SEL willBreakConstantSel = NSSelectorFromString(@"engine:willBreakConstraint:dueToMutuallyExclusiveConstraints:");     SwizzleInstanceMethod([UIView class], willBreakConstantSel, [self class], @selector(pr_engine:willBreakConstraint:dueToMutuallyExclusiveConstraints:));   }); }  - (void)pr_engine:(id)engine willBreakConstraint:(NSLayoutConstraint*)constraint dueToMutuallyExclusiveConstraints:(NSArray<NSLayoutConstraint*>*)layoutConstraints {   BOOL constrainsLoggingSuspended = [[self valueForKey:@"_isUnsatisfiableConstraintsLoggingSuspended"] boolValue];   if (!constrainsLoggingSuspended) {     NSLog(@"_UIViewAlertForUnsatisfiableConstraints would be called on next line, log this event");   }   [self pr_engine:engine willBreakConstraint:constraint dueToMutuallyExclusiveConstraints:layoutConstraints]; }  @end 

I test it on iOS Simulator 8/9/10, but I can't give any guarantee. This code is fragile (it can lead to crash on any system version update, parameters change, etc) and I will not recommend to use it in production (guess that it will not pass even automated review process). You have the last word, but you are warned.

However I think that you can use it in builds for internal/external testers to fix bugs in autolayout before production.

Noticed that you are using swift: you can add this code to your swift project with bridging header file.

Answers 2

The short answer is, this is a private API and you shouldn't be messing with it in production code…

…at least not without knowing the related dangers:

A) Apple will reject your app if you try to override SPIs like this in a product submitted to the app store. And if it slips through for some reason, they will catch it at some later date, and that is generally worse.

B) Method swizzling, like @Roman mentions in his answer, often brings with it some likelihood of you destabilizing whatever you're working on further (or in the future). I still worry when I user a third party library that someone is doing something brittle like this under the hood.

With those warnings out there, go ahead, override private methods and swizzle them to your hearts content. Just please don't ship that code.

Read More

Wednesday, March 9, 2016

How to force uitableview to resize a cell (after deactivating a height constraint)?

Leave a Comment

I am trying to put an extendable UITableViewCell by tapping on a button.

I am using the constraints to force the dynamic UITextView to tell the UITableViewCell the its new height. (using autolayout and UITableViewAutomaticDimension)

This works as expected without the button: The height of the UITableViewCell depends on the UITextView's height.

Having a constraint on the UITextView to maximize the size of the cell, when tapping the button (the cell is collapsed), I want to remove height constraint to the UITextView (that is limiting the cell height) and update the cell accordingly. Here's the extend method:

-(void)extendCellWasTapped:(UITableViewCell*)senderCell{      MAFollowingPostTableViewCell *cell = (MAFollowingPostTableViewCell*)senderCell;      NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];      if (![self.arrayExtendedTitlesAtIndexPaths containsObject:indexPath]) {         [self.arrayExtendedTitlesAtIndexPaths addObject:indexPath];     }      if ([self.tableView.indexPathsForVisibleRows containsObject:indexPath] ) {         dispatch_async(dispatch_get_main_queue(), ^(void){              [NSLayoutConstraint deactivateConstraints:@[cell.constraintTextViewHeight]];             // CGPoint offset = self.tableView.contentOffset;              [self.tableView beginUpdates];             [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];             [self.tableView endUpdates];  // I would like to minimize the animations as well here.. but thats another //problem //            [self.tableView.layer removeAllAnimations]; //            [self.tableView setContentOffset:offset animated:NO]; //            [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];          });     } } 

If I tap the button and then scroll to a similar cell, it is already expanded. So I am missing something here. I already tried to do [cell updateConstraints] after deactivating the constraint, but it doesn't work.

UPDATE

At first, the button doesn't show up for some reason. And I noticed that (with the same code) if I scroll down and then up, the button shows up and, if I try to extend it, it works.

UPDATE

This is my UIViewController :

http://www.gfycat.com/FairBossyAfricanporcupine

Notice that the extend button is not there, but once I scroll down/up it comes shows up and it extends the cell once I tap on the extend button.

What am I missing here?

4 Answers

Answers 1

To do such a thing, you shouldn't rely on constraint, but on tableView(_:heightForRowAtIndexPath:) you just have to give the right height depending on the context.

Pushing your button would trigger a change so tableView(_:heightForRowAtIndexPath:) returns a different value for your cell that you extend.

And just after doing this trigger, just do:

[self.tableView beginUpdates]; [self.tableView endUpdates]; 

without anything between them, it will trigger the "natural animation" of UITableView and do exactly what you want

Answers 2

Are forgetting to remove indexpath from self.arrayExtendedTitlesAtIndexPaths ?

if (![self.arrayExtendedTitlesAtIndexPaths containsObject:indexPath]) {     [self.arrayExtendedTitlesAtIndexPaths addObject:indexPath]; } else {    [self.arrayExtendedTitlesAtIndexPaths removeObject:indexPath]; } 

Answers 3

If the button isn't there and while you scrolling it show again surely you have a problem with reusability.

You're probably decide about to show or hide button in cellForRowAtIndexPath:. If you have a condition there try to show this button always, and if this will work as expected then hide a button inside a cell whenever this constraint is there or not. The right method is prepareForReuse inside UITableViewCell subclass.

Answers 4

Call [cell layoutSubviews]; once your changes are completed.

Read More