I am looking for a way to enter a label within a table cell that also has a disclosure indicator. The problem i'm having at the moment is that it seems like the disclosure indicator is being ignored when calculating the label's positions
Heres a picture:
So as you can see the label is centred in the area between the left side of the cell and the left side of the indicator, if it was centred in the cell it would sit below the nav bar heading.
Any help is appreciated thankyou
From within the storyboard
Okay, first an explanation for your issue. It has to do with the anatomy of a UITableViewCell
. With anatomy, I mean the fact that the UITableViewCell
for you is just a container for another container, which is the contentView
(you can also see this one in your storyboard).
When you are operating in Storyboards, you are solely operating on the contentView
, not on the actual UITableViewCell
. So, when you setup your UILabel
to be centered on the X-axis with AutoLayout, AutoLayout will always try to center it within the contentView
, not in the outer container (i.e. the UITableViewCell
). Then, when you add a disclosure indicator to the UITableViewCell
, the contentView
automatically gets shrinked in its width because the cell makes space for the disclosure indicator and wants to prevent you from adding UI elements in the right area that is reserved for the disclosure indicator.
Now, you have a few options around this:
UIImageView
with an image that looks identical.To not be bound to any constants you can calculate the difference in widths of frame
and contentView.frame
. So first create an outlet collection like so:
@property (strong, nonatomic) IBOutletCollection(NSLayoutConstraint) NSArray *centerConstraintsToOffset;
Then add the center constraints that you want to be centered horizontally in cell to that outlet collection:
And finally add this code to your cell:
override func layoutSubviews() {
super.layoutSubviews()
for constraint in centerConstraintsToOffset {
constraint.constant = (frame.size.width - contentView.frame.size.width) / 2.0
}
}
This also gives you flexibility of adding or removing cell accessories on the go, and your views will always be perfectly center aligned. Even if you remove the accessory at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With