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?
viewForBaselineLayout
is deprecated so you have to use
viewForFirstBaselineLayout
example
- (UIView *)viewForFirstBaselineLayout {
// Use subLabel view for handling baseline layouts
return self.subLabel;
}
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
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.
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