Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a custom UIView that defines a baseline?

Using the NSLayoutConstraint class, it is possible to create a constraint that is based on a view's baseline (NSLayoutAttributeBaseline). However, I haven't seen any documentation that describes how a UIView actually provides a baseline value to the auto layout system.

If I wanted to create a custom UIView subclass that defines a baseline, how would I do it? NSView defines a baselineOffsetFromBottom method that I assume is involved somehow on OS X, but how does this work in iOS?

like image 264
Greg Brown Avatar asked May 06 '13 20:05

Greg Brown


3 Answers

viewForBaselineLayout 

is deprecated so you have to use

viewForFirstBaselineLayout

example

- (UIView *)viewForFirstBaselineLayout  {
    // Use subLabel view for handling baseline layouts
    return self.subLabel;
}
like image 76
Kofi Sammie Avatar answered Nov 06 '22 02:11

Kofi Sammie


From the UIView docs:

viewForBaselineLayout

Returns a view used to satisfy baseline constraints.

- (UIView *)viewForBaselineLayout

Return Value

The view the constraint system should use to satisfy baseline constraints

like image 39
matt Avatar answered Nov 06 '22 03:11

matt


I've just used Hopper disassembler to look at UILabel in iOS 8.1, and it implements methods _baselineOffsetFromBottom and _firstBaselineOffsetFromTop, which are in turn called by -[UIView nsli_lowerAttribute:intoExpression:withCoefficient:forConstraint:], so UIKit has private methods similar to the one OS X has, they are just not exposed to the public.

_baselineOffsetFromBottom and _firstBaselineOffsetFromTop are implemented by UIView (returning 0), UILabel and UITextView. There's also a class named _UIGlintyStringView that implements _baselineOffsetFromBottom; no other UIKit classes have these methods.

Btw when the baseline of a view changes, it performs something like:

__UITagLayoutConstraintsForConstantChangeForSelectedAttributes(self, __UILayoutAttributeIsBaselineAttribute)

Doesn't seem like there's anything extra-special that couldn't be exposed to the public; perhaps they didn't feel like there's a need or wanted to discourage people from writing their own labels. UILabel is a fairly complicated class involving a custom CoreAnimation layer (_UILabelLayer) and a whole lot of trickery, including quite a bit of code for accessibility support.

like image 26
Andrey Tarantsov Avatar answered Nov 06 '22 02:11

Andrey Tarantsov