Showing posts with label autolayout. Show all posts
Showing posts with label autolayout. 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

Wednesday, January 3, 2018

UIScrollView ContentView dynamic height constraints

Leave a Comment

I am facing issue with contentView height constraints. All labels have dynamic height i.e no fixed height. I have read somewhere to set height equal to scrollview height.

The height of ViewController is currently 870px, scrollview height is 757px. I have no idea how can i set height in AutoLayout , as I am unable to scroll after a certain point.

Appearing in Simulation ViewController in main.Storyboard

I have set UIScrollView first then I added UIView as the child of the UIScrollView then I added 2 UIImageView and few UILabels, the size of UILabel is dependant on the content and content is not fixed. Since the height of UIView is static, when the content of UILabel is quite big, then I am unable to scroll after a certain point.

2 Answers

Answers 1

If what you mean is that you want the scroll view to be the same height/width as the container view:

  1. Go to the storyboard and locate the view
  2. Press "ctrl" and drag from the scroll view to one of the edges of the parent container
  3. Do the same step for all 4 edges (top,left,down,right edges of the scroll view)
  4. You might need to set the constraint to "0" (number of margin pixels from the parent)

Try to follow this picture (make sure all of the lines are bold (turned on) and set the value in the text box to "0":

enter image description here

Answers 2

Do it this way:

  1. Add the scroll view to your view controller and do not set any constraints to it.
  2. Start adding your subviews (images, labels etc) in your scroll view and set the desired constraints. For labels, you don't need to set the height, as they will auto-resize their height depending on content. For other subviews, also set the height or other constraints that will later determine the height (i.e. aspect ratio). If your scroll view gets too small for all the subviews you want to add, drag from its bottom to increase its height. It's important to keep all the subviews inside the scroll view and chain them one to another.
  3. For the last label in the scroll view, add a bottom constraint to the scroll view.
  4. Add margin constraints from your scroll view to the main view (top, leading, bottom and trailing).

Since all subviews are chained and pinned to top and bottom inside the scroll view and the scroll view is pinned to the storyboard's view, this will work.

Do not set the height of the scroll view. Setting it to 757 px is wrong because it renders your scroll view below the screen on devices with a height lower than 757px.

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, October 28, 2017

Following cursor in dynamic UITextView with UITableView no longer working in iOS 11

Leave a Comment

I created a UITextView which is sized dynamically within a UITableViewCell as a person types.

On iOS 10 the UITextView's cursor is followed automatically with very little code needed.

In the UITextViewDelegate method textViewDidChange: I've used this code which updated the size of the text view without any jumping around.

func textViewDidChange(_ textView: UITextView) {     UIView.setAnimationsEnabled(false)     self.tableView.beginUpdates()     self.tableView.endUpdates()     UIView.setAnimationsEnabled(true)     self.tableView.contentOffset = currentOffset } 

In iOS 11 this no longer works and when I type the cursor disappears under the keyboard. Note that I didn't need any changes when the keyboard appeared.

I know that there were changes in iOS 11 related to how content insets work but have been unable to figure out what changes I'd need to make to make this work.

Where should I be looking to make these changes to fix it?

-- Update --

It would turn out that removing all of that code solves my problem in iOS 11 and iOS 11 handles scrolling down to follow the cursor as I type automatically without any problems.

The one issue I have remaining is that I can only type up to 28 lines of text into the UITextView before it stops updating the UITextViews size.

3 Answers

Answers 1

class TextViewTableCell: UITableViewCell {      @IBOutlet private weak var textView: UITextView! {         didSet {             textView.delegate = self             textView.isScrollEnabled = false         }     }      var textDidChangeHandler: (((text: String?, shouldScroll: Bool)) -> Void)?      func textViewDidChange(_ textView: UITextView) {         let size = textView.bounds.size         let newSize = textView.sizeThatFits(CGSize(width: size.width, height: .greatestFiniteMagnitude))          let shouldScroll = size.height != newSize.height ? textView.text.count == textView.selectedRange.location : false         textDidChangeHandler?((text: textView.text, shouldScroll: shouldScroll))     } } 

Inside you data source cellForRow method:

// dequeue TextViewTableCell cell cell.textDidChangeHandler = { [weak self] (text, shouldScroll) in     guard let this = self else { return }     // do whatever actions with text if needed     guard shouldScroll else { return }     UIView.performWithoutAnimation {         tableView.beginUpdates()         tableView.endUpdates()      }     tableView.scrollToRow(at: indexPath, at: .bottom, animated: false) } 

Also good to have minimum height constraint for text view (for e.g. >=44)

Answers 2

I am using the sabe method to update a textView, and it's working fine for more than 28 lines of text, make sure you have all this properties set:

textView.showsVerticalScrollIndicator = false textView.isScrollEnabled = false 

also when i define the textView text i call textView.sizeToFit()

Answers 3

From XCode 9, the calculation of row is automatic once you set properties in size inspector of tableview.Here, You can check this in image and I mad one change in func textViewDidChange(_ textView: UITextView) Below is my code

 func textViewDidChange(_ textView: UITextView) {         UIView.setAnimationsEnabled(false)         self.tableView.beginUpdates()         self.tableView.endUpdates()         UIView.setAnimationsEnabled(true)         textView.sizeToFit()     } 

and It's working fine for me in iOS 11

Read More

Thursday, August 3, 2017

Why might Autolayout constraints not appear at runtime?

Leave a Comment

I am trying to create a custom subclass of UITableViewCell that displays an image and a few labels to the right of the image. I have my UIImageView and UILabels arranged in stack views, the outermost of which I pinned to all four sides of the content view. Screenshot of storyboard Screenshot of constraints

But when I run the app in the simulator, I do not see the image views. Debugging the view hierarchy, I see they are getting clipped. Screenshot of view hierarchy

And digging in a little further by focusing on the outermost stack view with "Show Constraints" on, I don't see my auto layout constraints at all (instead I get an ambiguous position runtime warning for each of the outermost stack views). Screenshot of view hierarchy focused on stack view

The text label that expands to the right is set up with 0 lines and the table view gets a constant estimatedRowHeight value and its rowHeight set to UITableViewAutomaticDimension, so I think if these constraints were working, the rows in the table would size to fit the content. Perhaps notably, any width or height auto layout constraint I add does appear when I debug the view hierarchy, so I know some constraints are present at runtime, I just cannot for the life of me figure out why the constraints relative to the content view are not.

2 Answers

Answers 1

After wrestling with this for a long time and having a much more experienced developer look over my project, it seems as if there was nothing wrong with the way it was set up. Recreating the table view cell from scratch with exactly the same layout and constraints and using the exact same code fixed this issue. I had messed around with the stack views and constraints quite a bit before this started happening, so it might be possible to get Xcode into a place where it does not properly set up constraints when you run the app in the simulator.

Answers 2

Try to solve all warnings which are printed into your console log when you run your application and viewing this screen. Because you can not ignore warnings always, many warnings you must have to remove by correcting or solving issues in your constraint. And that is the only solution which helps you most of the time.

Read More

Tuesday, August 1, 2017

searchBar overlapped by section header view

Leave a Comment

I put the searchBar inside the tableHeaderView. Everything works fine on iphone 6 but on iphone 5s I get this weird result?

 override func viewDidLoad() {     super.viewDidLoad()     tableView.delegate = self     tableView.dataSource = self     tableView.sectionIndexColor = Constants.Colors.ThemeGreen     tableView.sectionIndexBackgroundColor = UIColor.clearColor()     tableView.sectionIndexTrackingBackgroundColor = UIColor.clearColor()     tableView.contentInset = UIEdgeInsetsMake(0, 0, CGFloat(Constants.Dimensions.TabBarHeight), 0)     resultSearchController = UISearchController(searchResultsController: nil)     resultSearchController.searchResultsUpdater = self     resultSearchController.dimsBackgroundDuringPresentation = false     resultSearchController.definesPresentationContext = true     tableView.tableHeaderView = resultSearchController.searchBar     resultSearchController.searchBar.sizeToFit()   //Fetch data for the first time     do{       try fetchedResultsController.performFetch()       listHeaderView?.count = "\(fetchedResultsController.fetchedObjects!.count)"     }catch{       print("Error - Couldn't fetch list")     } 
  • NOTE: I'm using a NSFetchedResultController to retrieve the data

enter image description here

4 Answers

Answers 1

Here is the solution. Don't call sizeToFit() AFTER putting the searchBar in tableHeaderView but call it BEFORE. What the hell is going on behind the scene... I wonder..

resultSearchController.searchBar.sizeToFit() //Important to call sizeToFit BEFORE adding it to tableHeaderView or you get layout issues tableView.tableHeaderView = resultSearchController.searchBar 

Answers 2

It seems only below line of code does work ... nothing else seems to work right now.

self.tableView.beginUpdates()        // self.tableView.setTableHeaderView(headerView: self.filterView!)         //self.tableView.reloadData()         self.tableView.layoutIfNeeded()         self.tableView.layoutSubviews()         self.tableView.endUpdates() 

everytime your table resize or change constraints you need to call above code.

Answers 3

@mihir mehta

You can also try the same as

searchControl.searchBar.clipToBounds = true 

I think it works for your code.

Answers 4

Try this it may work

resultSearchController.clipToBounds = true

You can also try the same as

searchControl.searchBar.clipToBounds = true 

I think it works for your code.

Read More

Thursday, July 6, 2017

Multiple flexible height items - how to set the autolayout priorities?

Leave a Comment

Say you have (for example) a table cell layout with more than one dynamic flexible-height items,

They are linked vertically one to the other in the obvious way.

enter image description here

It seems very difficult to make this work, and very undocumented.

You'd expect that: you set the compression resistance of all the expandable items to 751. But that doesn't work.

After random experimentation, it seems to me that surprisingly you have to do something like this:

have the compression/hugging of the overall view on 250 and 750,

enter image description here

then strangely enough, for the three text views in the example, the priorities have to

...sequentially increase...

enter image description here

And, I think you have to make one of them "one lower" than the overall view - in the example one of them would be 749.

It's difficult/impossible to find the exact "formula" to make it work consistently.

What the heck is the logic of this? Is it just a pure bug in iOS?

Has anyone found the "correct formula" for making a number of expandables work in a cell?

  • priorities for the three text views

  • priorities for the overall holder view

cheers

2 Answers

Answers 1

Your question is not very clear to me. However, here's a good recipe to stack text views (whether or not you use a stack view for constraining them doesn't matter):

1. Disable scrolling for all your UITextViews:

Disable scrolling in Identity Inspector

Reason: If scrolling is enabled, a UITextView does not have a defined intrinsicContentSize. See this answer. Without an instrinsic content size, the content hugging and compression resistance ("CHCR") priorities have no meaning or effect.

2. Give each view along one axis a different priority for CHCR:

More precisely: Give all views that are connected with constraints along one axis a different CHCR priority that are not constrained in size along that axis (i.e. that don't have a fixed width / height constraint).

In your particular example, your setup shown in the screenshots is a correct solution: Each of the three text views has a different content hugging and a different compression resistance priority. As a general rule you should start with the default values (750 / 250) and only slightly increase or decrease them as you did.

In case you use a table view with self-sizing cells (by setting its estimatedItemSize), the CHCR priorities won't matter at runtime because the cell will automatically resize to accommodate enough space for all three text views. You just need to set those priorities to "silence" Interface Builder.

If you use fixed-height table view cells however, the CHCR priorities are quite important because they determine

  • which of the views will shrink first if there's not enough space inside the cell (it's the view with the lowest compression resistance priority) and
  • which of the views will expand if there's more space inside the cell than the subviews actually need (it's the view with the lowest content hugging priority).

The CHCR priorities of the superview ("MV") is irrelevant as it's usually just a container view that does not have a defined intrinsicContentSize either. Its size is defined by the inner and outer constraints you add.


For more information on the CHCR priorities, see the chapter Intrinsic Content Size in the Auto Layout Guide.

Answers 2

When I am playing with cells that have a variable height I use:

tableView.estimatedRowHeight = 20.0 tableView.rowHieght = UITableViewAutomaticDimension 

These two cause the table view render its cells with the appropriate height. In order for the height to be computed though you should set the cell's data in tableView(cellForRowAt)

Read More

Monday, June 12, 2017

Move UITextField up when keyboard is overlapped

Leave a Comment

There is a subView presented on top of ViewA. Please find the screen layout below. When keyboard is shown on selecting UITextField even if its not overlapping with UITextField the view is scrolled up.

ViewA   -> UIButton  subView   -> UIScrollView         -> UITextField         -> UITextField      ViewA  ----------- |           | |           | |  Button   | |           | |           |  -----------     subView  -------------- |              | |              | |  UITextField | |  UITextField | |              |  -------------- 

I have registered keyboard notification

    - (void) viewWillAppear:(BOOL)animated {          [[NSNotificationCenter defaultCenter] addObserver:self                                                  selector:@selector(keyboardDidShow:)                                                      name:UIKeyboardDidShowNotification                                                    object:nil];          [[NSNotificationCenter defaultCenter] addObserver:self                                                  selector:@selector(keyboardWillBeHidden:)                                                      name:UIKeyboardWillHideNotification                                                    object:nil];     }   - (void) keyboardDidShow:(NSNotification *)notification {              NSDictionary* info = [notification userInfo];             CGRect kbRect = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];              UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbRect.size.height, 0.0);             self.scrollViewIb.contentInset = contentInsets;             self.scrollViewIb.scrollIndicatorInsets = contentInsets;              CGRect aRect = self.viewSelf.frame;             aRect.size.height -= kbRect.size.height;             CGRect frame = [self.viewSelf convertRect:self.activeField.frame toView:self.viewSelf.superview];             if (!CGRectContainsPoint(aRect, frame.origin) ) {                 [self.scrollViewIb scrollRectToVisible:self.activeField.frame animated:YES];             }     }  - (void) keyboardWillBeHidden:(NSNotification *)notification {          self.scrollViewIb.scrollEnabled = true;          UIEdgeInsets contentInsets = UIEdgeInsetsZero;         self.scrollViewIb.scrollIndicatorInsets = contentInsets;         [self.scrollViewIb setContentOffset:CGPointZero animated:false];  } 

4 Answers

Answers 1

There's a minor mistake in the coordinate system conversion: convertRect:toView: converts from the coordinate system of the receiver to the coordinates of the passed view.

If self.activeField.frame is a rectangle in the coordinate system of self.scrollViewIb as the code implies, then the conversion should go like this...

    CGRect frame = [self.scrollViewIb convertRect:self.activeField.frame toView:self.view]; 

Notice that I also suggest changing self.viewSelf.superview to self.view. If this code is running in the view controller that contains all of these subviews, then self.view should be sufficient and correct.

Answers 2

I think the problem is that you are always scrolling up, no matter if the keyboard overlaps your textfield or not.

You would have to get the frame of the textfield, calculate the distance to the bottom of the screen and check if the keyboard height (plus possible toolbar on top of it) would overlap your textfield and only then scroll up.

Anyways, I personally gave up on implementing scroll up behavior again and again. I now switched to using IQKeyboardManager. Simply install it as a Pod in your project and call IQKeyboardManager.sharedManager().enable = true in application(didFinishLaunchingWithOptions) and you are all set.

You even get a toolbar with next/previous and done button for free.

Answers 3

Don't get worry when we are in the world with the lots of open libraries.

Use KeyboardLib Lib by adding it to code or by the pod.

Just build it. On every Keyboard open that will show option for the Next, previous arrow with the Done button. Zero line of code with automatic event handling.

May be this one will solve the issue and a solution for the app betterment.

Answers 4

               Add this in your Controller or the other way is to create a category on UITextField               static CGFloat  const  MINIMUM_SCROLL_FRACTION = 0.4;             static CGFloat  const  MAXIMUM_SCROLL_FRACTION = 0.8;             static CGFloat  const  PORTRAIT_KEYBOARD_HEIGHT = 185;             static CGFloat  const  PORTRAIT_KEYBOARD_HEIGHT1 = 230;             static CGFloat  const  LANDSCAPE_KEYBOARD_HEIGHT = 140;             static CGFloat  const  KEYBOARD_ANIMATION_DURATION = 0.3;`                  - (void)textFieldDidBeginEditing:(UITextField *)textField view:(UIView *)view{CGRect textFieldRect = [view.window convertRect:textField.bounds fromView:textField];CGRect viewRect = [view.window convertRect:view.bounds fromView:view];CGFloat midline = textFieldRect.origin.y + 0.5 * textFieldRect.size.height;CGFloat numerator = midline - viewRect.origin.y - MINIMUM_SCROLL_FRACTION * viewRect.size.height;CGFloat denominator = (MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION) * viewRect.size.height;                 CGFloat heightFraction = numerator / denominator;                 if (heightFraction < 0.0)                 {                     heightFraction = 0.0;                 }                 else if (heightFraction > 1.0)                 {                     heightFraction = 1.0;                 }                 UIInterfaceOrientation orientation =                 [[UIApplication sharedApplication] statusBarOrientation];                 if([[ UIScreen mainScreen ] bounds ].size.height == 568)                 {                     if (orientation == UIInterfaceOrientationPortrait ||                         orientation == UIInterfaceOrientationPortraitUpsideDown)                     {                         animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);                     }                     else                     {                         animatedDistance = floor(LANDSCAPE_KEYBOARD_HEIGHT * heightFraction);                     }                 }                 else{                     if (orientation == UIInterfaceOrientationPortrait ||                         orientation == UIInterfaceOrientationPortraitUpsideDown)                     {                         animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction + 23);                     }                     else                     {                         animatedDistance = floor(LANDSCAPE_KEYBOARD_HEIGHT * heightFraction + 23);                     }                 }                  CGRect viewFrame = view.frame;                 viewFrame.origin.y -= animatedDistance;                 [UIView beginAnimations:nil context:NULL];                 [UIView setAnimationBeginsFromCurrentState:YES];                 [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];                 [view setFrame:viewFrame];                 [UIView commitAnimations];     }                  - (void)textFieldDidEndEditing:(UITextField *)textField view:(UIView *)view          CGRect viewFrame = view.frame;         viewFrame.origin.y += animatedDistance;                 [UIView beginAnimations:nil context:NULL];                 [UIView setAnimationBeginsFromCur rentState:YES];                 [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];                 [view setFrame:viewFrame];                 [UIView commitAnimations];             } 
Read More

Sunday, June 4, 2017

UICollectionView, full width cells, allow autolayout dynamic height?

Leave a Comment

Here's a fairly basic question about current iOS development, to which I've never found a good answer.


In a (say) vertical UICollectionView ,

Is it possible to have full-width cells, but, allow the height to be controlled by autolayout?

If so how?

This strikes me as perhaps the "most important question in iOS with no really good answer."

6 Answers

Answers 1

Problem

You are looking for automatic height and also want to have full in width , it is not possible to get both in using UICollectionViewFlowLayoutAutomaticSize. why you don't take UITableVIew instead of UICollectionView in which you can just return in the heightForRow as UITableViewAutomaticDimension it will be managed automatically . anyways you want to do using UICollectionView so below is the solution for you.

Solution

Step- I: : Calculate the expected height of Cell

1. : If you have only UILable in ColllectionViewCell than set the numberOfLines=0 and that calculated the expected height of UIlable , pass the all three paramters

 func heightForLable(text:String, font:UIFont, width:CGFloat) -> CGFloat{   // pass string ,font , LableWidth           let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))         label.numberOfLines = 0         label.lineBreakMode = NSLineBreakMode.byWordWrapping         label.font = font         label.text = text         label.sizeToFit()          return label.frame.height     } 

2. : if your ColllectionViewCell contains only UIImageView and if it's is supposed to be dynamic in Height than you need to get the height of UIImage (your UIImageView must have AspectRatio constraints )

// this will give you the height of your Image let heightInPoints = image.size.height let heightInPixels = heightInPoints * image.scale 

3. if it contains both than calculated their height and add them together.

STEP-II : Return the Size of CollectionViewCell

1. Add UICollectionViewDelegateFlowLayout delegate in your viewController

2. Implement the delegate method

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {  // This is Just for example , for the scenario Step-I -> 1  let yourWidthOfLable=self.view.size.width let font = UIFont(name: "Helvetica", size: 20.0)  var expectedHeight = heightForLable(array[indePath.row], font: font, width:yourWidthOfLable )    return CGSize(width: view.frame.width, height: expectedHeight) } 

i hope this will help you out .

Answers 2

Not sure if this qualifies as a "really good answer", but it's what I'm using to accomplish this. My flow layout is horizontal, and I'm trying to make the width adjust with autolayout, so it's similar to your situation.

extension PhotoAlbumVC: UICollectionViewDelegateFlowLayout {   func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {     // My height is static, but it could use the screen size if you wanted     return CGSize(width: collectionView.frame.width - sectionInsets.left - sectionInsets.right, height: 60)    } } 

Then in the view controller where the autolayout constraint gets modified, I fire off an NSNotification.

NotificationCenter.default.post(name: NSNotification.Name("constraintMoved"), object: self, userInfo: nil) 

In my UICollectionView subclass, I listen for that notification:

// viewDidLoad NotificationCenter.default.addObserver(self, selector: #selector(handleConstraintNotification(notification:)), name: NSNotification.Name("constraintMoved"), object: nil) 

and invalidate the layout:

func handleConstraintNotification(notification: Notification) {     self.collectionView?.collectionViewLayout.invalidateLayout() } 

This causes sizeForItemAt to be called again using the collection view's new size. In your case, it should be able to update given the new constraints available in the layout.

Answers 3

There are couple of ways you could tackle this problem.

One way is you can give the collection view flow layout an estimated size.

(assuming you are using storyboards and the collection view is connected via IB)

override func viewDidLoad() {     super.viewDidLoad()     let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout     layout?.estimatedItemSize = CGSize(width: 375, height: 200) // your average cell size } 

For simple cells that will usually be enough. If size is still incorrect, in the collection view cell you can override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes, which will give you more fine grain control over the cell size. Note: You will still need to give the flow layout an estimated size.

Alternatively, instead you can use a sizing cell to calculate the size of the cell in the UICollectionViewDelegateFlowLayout.

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {     let width = collectionView.frame.width     let size = CGSize(width: width, height: 0)     // assuming your collection view cell is a nib     let sizingCell = UINib(nibName: "yourNibName", bundle: nil).instantiate(withOwner: nil, options: nil).first as! YourCollectionViewCell     sizingCell.autoresizingMask = [.flexibleWidth, .flexibleHeight]     sizingCell.frame.size = size     sizingCell.configure(with: object[indexPath.row]) // what ever method configures your cell     return sizingCell.contentView.systemLayoutSizeFitting(size, withHorizontalFittingPriority: UILayoutPriorityRequired, verticalFittingPriority: UILayoutPriorityDefaultLow) } 

While these are not perfect production ready examples, they should get you started in the right direction.

Answers 4

You have to inherit the class UICollectionViewDelegateFlowLayout on your collectionViewController. Then add the function:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {     return CGSize(width: view.frame.width, height: 100) } 

Using that, you have the width size of the screen width.

And you now have a collectionViewController with rows as a tableViewController

If you want the size of the height of each cell to be dynamically, perhaps you should create custom cells for each cell you need.

Answers 5

Personally I found the best ways to have a UICollectionView where AutoLayout determines the size while each Cell can have a different size is to implement the UICollectionViewDelegateFlowLayout sizeForItemAtIndexPath function while using an actual Cell to measure the size.

I talked about this in one of my blog posts: https://janthielemann.de/ios-development/self-sizing-uicollectionviewcells-ios-10-swift-3/

Hopefully this one will help you to achieve what you want. I'm not 100% sure but I believe unlike UITableView where you can actually have a fully automatic height of cells by using AutoLayout inconjunction with

tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 44 

UICollectionView does not have such a way of letting AutoLayout determine the size because UICollectionViewCell does not necessarily fills the whole width of the screen.

But here is a question for you: If you need full screen width cells, why do you even bother using the UICollectionView over a good old UITableView which comes with the auto sizing cells?

Answers 6

From iOS 10, we've got new API on flow layout to do that.

All you have to do is set your flowLayout.estimatedItemSize to a new constant, UICollectionViewFlowLayoutAutomaticSize.

Source: http://asciiwwdc.com/2016/sessions/219

Read More

Sunday, April 16, 2017

How to prevent content offsetting when increasing content size

Leave a Comment

tl;dr I don't want increases in the sizes of UIViews above the top of the UIScrollView's content window to push the content below it downwards.

I have a UIScrollView that displays a list of many UIStackViews, and one of the benefits of UIStackViews is that when you set isHidden = false to one of its subviews, it resizes automatically to compensate for the new view.

Now, each list item has one of these UIStackViews, and the user can press a button that sets isHidden = false to a subview in each one, all at once. That means, each list item will increase by an amount equal to the height of the unhidden view (the same height for each stack view).

There is no problem if the scrollview's contentOffset is zero, because all the increases in height will just push all the rest of the content downwards, and the user will still be at the top of the scrollview after all the views have unhidden.

The problem is when the user is not at the top of the scrollview. When this is the case, and the user presses the button that unhides all the views, the increases in height will push all the views downwards, giving the appearance of scrolling upwards. The further down the user is scrolled in the list, the more views above it, and the greater the content shift when the user presses the button.

The behavior I'm looking for is the same as when the user presses the button when they are scrolled to the top of the view, but at any scroll position. In other words: regardless of where the user is scrolled too, when they press the button, the only views that are pushed down are the ones below the top of the scrollview's content window.

Any idea how to accomplish this?

1 Answers

Answers 1

Okay, so let me see if I understand your question properly.

This is the state of the Scroll View

 A  B  C  D  E 

When the user presses the "expand all" button, it looks like this:

 A  -1  -2  -3  B  -1  +-a  +-b  -2  C  -1  -2  -3  D  -1  -2  E  -1  -2  -3  -4 

The problem is that if the user is currently looking at

+---+ |D  | |E  | +---+ 

(which are the 4th and 5th items in the list) they end up seeing in the expanded list:

+---+ |B  | |-1 | +---+ 

But they should be seeing items D that they were looking at prior.

I would probably recommend using a UITableView as you can store the currently visible TableViewCells and then as the view animates, scroll to the current cell (which should keep it relatively in-view).

In your case, with the UIScrollView what I would recommend is capturing the current visible subviews (using current contentOffset/Size and the frames of the subviews), then figuring out where they are after the view animates it's size transition, and then scroll to the new position.

This is, as I mentioned, a task better suited to UITableView or UICollectionView where the parent objects are tracked and cached by the OS and there are specific rules governing the insertion/deletion of rows/cells.

HtH

Read More

Tuesday, March 21, 2017

How can I fix or workaround this tableView textField autolayout glitch?

Leave a Comment

I think the root cause is that the estimatedRowHeight is used to make assumptions about the underlying UIScrollView.contentOffset, but this will always be wrong by definition as it is a estimate. The real row heights are completely different depending on the cell content and device orientation.

Even if I implement estimatedHeightForRowAtIndexPath to provide closer estimates the glitches are still there.

So when you start at the top and scroll down all is well because the TableView learns the actual cell heights as it goes keeping the contentOffset in sync with the cell positions. But as soon as you rotate all the real cell heights change so the UITableView is now way out of sync, it doesn't know where to scroll to.

But there are even stranger things happening too, sometimes the UITextField cell will end up on top of another cell, and remain stuck there...

Anyway I have boiled it all down to a simple example.

https://github.com/trapper-/autolayout-glitch

  • Test with iPhone and if using simulator then enable the software keyboard.
  • You will see many visual glitches just playing around scrolling, selecting fields and rotating.
  • For a simple repeatable example.
  • Scroll down to the bottom.
  • Select one of the last couple of UITextField's, so that the UITableView will need to scroll to ensure the field will be visible.
  • Rotate the device.

1 Answers

Answers 1

I toyed with your code for a few minutes, because I struggled through similar issues. I was hopeful I could help, but I didn't get it fully fixed.

What I can offer is that I did make some progress.

When the device rotates, you should implement the UIViewcontroller methods that tell you it will happen, and did happen. When it will happen, cache off the visible rows. Then after it did, reload the table and scroll to those visible rows.

It looks like this:

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {     // Save the visible row position     self.visibleRows = [self.tableView indexPathsForVisibleRows]; }  -(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {     [self.tableView reloadData];     // Scroll to the saved position prior to screen rotate     [self.tableView scrollToRowAtIndexPath:[self.visibleRows objectAtIndex:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO]; } 

visibleRows is an array @property on your ViewController.

This made it go to the rightish place ( I suspect that if you actually stored off the individual cell that the user was manipulating, this would get you 100% to the right cell every time.

What this did not do, is that there were still the dancing UITextFields being laid out incorrectly (on occasion) with several device rotations.

Again, not a solution - but I wanted to share what I saw so hopefully this helps you find the solution.

Good Luck!

Read More

Friday, February 3, 2017

UILabel with custom UIEdgeInsets truncating in UITableViewCell

Leave a Comment

I have an UITableView with cells that contains an UILabel. The UILabel have a custom UIEdgeInset. I subclassed the UILabel and set the UIEdgeInsets like this:

override func drawText(in rect: CGRect) {     super.drawText(in: UIEdgeInsetsInsetRect(rect, insets)) }  override var intrinsicContentSize: CGSize {     var contentSize = super.intrinsicContentSize     contentSize.width += leftInset + rightInset     contentSize.height += topInset + bottomInset     return contentSize } 

But the label gets truncated sometimes when I have more lines in the UILabel. I've already configured the row height to UITableViewAutomaticDimension and set the estimatedRowHeight. Also the constraints are fine. The problem seems to be when I'm setting the UIEdgeInsets since it works fine if I don't customize it.

Probably I should tell the cell to update the constraints after setting the insets, but I couldn't do this so far.

The constraints where added in storyboard. Bottom, Top, Leading and Trailing are related to the superview (UITableViewCell). All constants set to 0.

In cellForRowAtIndexPath the code is as follows:

let cell = tableView.dequeueReusableCell(withIdentifier: "AnswersCell", for: indexPath) as! AnswerCell   cell.answerLabel.text = alternatives[indexPath.row] return cell 

3 Answers

Answers 1

There are two issues that I can see:

  1. The width of the label's intrinsicContentSize is increased by your left and right content insets. The intrinsic width of the label's content should either stay the same or be decreased, depending on whether you regard the intrinsic size as including padding or not.

  2. During auto layout of a multiline label, UILabel does not compute its height using the width provided by its intrinsicContentSize property, but instead uses preferredMaxLayoutWidth, which has not been adjusted to take account of your content insets.

Suggested solutions below.

1. Correct the size returned by intrinsicContentSize

In your current implementation, the rect passed to super.drawText(in:) is the default rect inset by your content insets (i.e. the default rect less padding), but the value of intrinsicContentSize is the default size increased by your content insets (i.e. the default size plus padding). In other words, the size of the rect in which the text is drawn is not the same as the intrinsic content size.

Specifically, the width of the rect in which the text is drawn does not include padding, whereas the width of the intrinsic content size not only includes padding but adds that padding to the width of the table view cell (being the width returned by super.intrinsicContentSize).

I assume your intention was for the intrinsic content size of your label subclass to be the size of the content (text) plus any content inset (padding). If so, delete this line:

contentSize.width += leftInset + rightInset 

The effect is that the intrinsic width of the label will be determined by its auto layout constraints and hence by the width of the table view cell. The intrinsic width of the label will include padding in the same way that the intrinsic height includes padding.

2. Set an appropriate value for preferredMaxLayoutWidth

The above is not sufficient to achieve your goal, because in performing auto layout for a multiline label, UILabel does not use its intrinsic width to compute its height, but instead uses the value of preferredMaxLayoutWidth. So correcting the width of the label's intrinsic content size is not enough to correct the height computed by auto layout.

The header file for UILabel provides the following comment for preferredMaxLayoutWidth:

// If nonzero, this is used when determining -intrinsicContentSize for multiline labels

In your case, the desired value for preferredMaxLayoutWidth is the auto layout width of the label (i.e. the width of the table view cell) less any left and right content insets. The most practical way to set that property is in your table view cell subclass, because that is the most straightforward place to access the width of the table view cell during auto layout.

When performing auto layout for self-sizing table view cells, UITableView calls systemLayoutSizeFitting(_:withHorizontalFittingPriority:verticalFittingPriority) on each cell. (See WWDC 2014 Session 226.) The fitting size passed to that method is the width of the table view with a zero height, and the horizontal fitting priority is UILayoutPriorityRequired.

So, override that method and set the desired value for preferredMaxLayoutWidth:

//  AnswerCell.swift  @IBOutlet weak var answerLabel: AnswerLabel!  override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {     answerLabel.preferredMaxLayoutWidth = targetSize.width - answerLabel.insets.left - answerLabel.insets.right     return super.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: horizontalFittingPriority, verticalFittingPriority: verticalFittingPriority) } 

The effect is that, in computing its height during auto layout, UILabel uses a value of preferredMaxLayoutWidth that has been adjusted for your content insets, which ensures that UITableView receives the correct heights for its cells.

Addendum

Alternatively, instead of all of the above, you could simply change the constraints on your label to inset the whole label, either directly in the content view of the table view cell or by embedding it in another subview of the content view.

Answers 2

Set these two properties of UILable from Attributes inspector section of storyboard

  1. Lines to 0
  2. Line break to word wrap

or you can also set these properties from code.

self.answerLabel.numberOfLines = 0 self.answerLabel.lineBreakMode = .byWordWrapping 

and put below code in your UILable's subclass

class CustomLabel: UILabel {  @IBInspectable var topInset: CGFloat = 5.0 @IBInspectable var bottomInset: CGFloat = 5.0 @IBInspectable var leftInset: CGFloat = 20.0 @IBInspectable var rightInset: CGFloat = 5.0  override func drawText(in rect: CGRect) {     let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)     super.drawText(in: UIEdgeInsetsInsetRect(rect, insets)) }  override var intrinsicContentSize: CGSize {     get {         var contentSize = super.intrinsicContentSize         contentSize.height += topInset + bottomInset         contentSize.width += leftInset + rightInset         return contentSize     } } 

}

try this.

Hope it will work for you..

Answers 3

I subclassed my Label like this:

class PaddingLabel: UILabel {      var topInset: CGFloat = 0     var bottomInset: CGFloat = 0     var leftInset: CGFloat = 0     var rightInset: CGFloat = 0      override func drawText(in rect: CGRect) {         let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)         super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))     }      override var intrinsicContentSize: CGSize {         get {             var contentSize = super.intrinsicContentSize             contentSize.height += topInset + bottomInset             contentSize.width += leftInset + rightInset             return contentSize         }     } } 

Maybe it's the get that's missing.

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