Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Centring UITableViewCell label with disclosure indicator

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:

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

enter image description here

like image 894
Joe Maher Avatar asked Apr 11 '15 06:04

Joe Maher


2 Answers

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:

  1. you can edit the constraint directly and add a constant to it (which has to be the same value that the label gets shifted when you'd remove the indicator)

enter image description here

  1. don't use the default disclosure indicator (i.e. don't tick the checkbox in Storyboards) and just add a UIImageView with an image that looks identical.
like image 194
nburk Avatar answered Sep 28 '22 06:09

nburk


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:

enter image description here

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.

like image 23
Pavel Gurov Avatar answered Sep 28 '22 06:09

Pavel Gurov