4

I have a custom meter view. And a label that shows the numeric value graphed by the meter. Using AutoLayout constraints, I want to align the baseline of the label with the bottom of the view.

When I ctrl drag between the two and choose to align bottoms, and then try to use the Size Inspector to tune it, it won't give me the option of baseline for the label (just Top, Bottom, and Center Y).

Is there no way to constrain the baseline of a label to match the bottom edge of another view in the Storyboard Editor?

Can I do it in direct code? What would an example of that look like?

Travis Griggs
  • 21,522
  • 19
  • 91
  • 167
  • You mean size inspector on the constraint? do you select the constraint then click on size inspector? because when I select that size inspector on the constraint I only get one field says constant?! – hasan Dec 01 '14 at 23:09
  • Click the `First Item` or `Second Item` drop down menus. You'll see a list of different constrainable attributes. Baseline is in there, but grayed out. – Travis Griggs Dec 01 '14 at 23:32
  • when you have two UILabel. select both of them and click the first item. baseline will not be grated. because, both have baseline att. – hasan Dec 01 '14 at 23:51
  • I think it must be done programmatically. Interesting question. +1 and favoured. waiting for answer. – hasan Dec 01 '14 at 23:54
  • Baseline is applicable for UILabel only. – pankaj nigam Aug 06 '19 at 20:13

2 Answers2

3

I determined that the Storyboard Editor just doesn't seem to want to do this directly. You can do it programmatically with something like this:

NSLayoutConstraint *constraint = [NSLayoutConstraint
    constraintWithItem: self.myView
    attribute: NSLayoutAttributeBottom
    relatedBy: NSLayoutRelationEqual
    toItem: self.myLabel
    attribute: NSLayoutAttributeBaseline
    multiplier: 1
    constant: 0];
[self.myView.superview addConstraint: constraint];

To make the storyboard experience happy, I used a bottom-to-bottom constraint and checked the Placeholder remove at build time option.

It's unfortunate that the secondAttribute property of NSLayoutConstraint is read-only. Otherwise, you could just create an outlet to the storyboard constraint, and just tweak that at viewDidLoad time.

Travis Griggs
  • 21,522
  • 19
  • 91
  • 167
0

Use following code

let constraint = NSLayoutConstraint(
    item: myLabel,
    attribute: .bottom,
    relatedBy: relation,
    toItem: myView,
    attribute: .bottom,
    multiplier: 1,
    constant: constant
)
myLabel.addConstraint(constraint)
Ajith Renjala
  • 4,934
  • 5
  • 34
  • 42
pankaj nigam
  • 381
  • 1
  • 6
  • 9