简体   繁体   中英

How to use auto-layout to move a UILabel relative to a UIView height?

I can't figure out how to use auto-layout to reposition a UILabel relative to a UIView height.

Example: If a UIView has a height of 50 points, and a UILabel is positioned at 10 points from the top and 30 points from the bottom, 在此处输入图片说明

how to maintain the UILabel position ratio if the UIView changes to a height of 70 points, more exactly to obtain 20 points from the top and 40 points to the bottom for the UILabel using auto-layout.

在此处输入图片说明

The only solution to this that I am aware of is to add a separate "spacing" view that is hidden. So if you want to maintain you relative 20% spacing on top you can add a hidden view that has 10px height and is at x: 0 y:0 relative to the superview. You then set the height of that view to be relative to the superview by setting the multiplier as 10/50 (height of your spacing view divided by the height of the superview).

Then you connect the vertical spacing of your test view to 0px of the spacing view. Once the layout changes the height of the invisible spacing view changes with the superview and the relateive Y position of your view is maintained.

I find it idiotic that I am reduced to doing this but I have not found another way that works in XCode 6.

Assume your label height is 20 . Set top label constraint to superview's centerY like this: 约束截图

With this config the label topY will be 10 for superview height of 50 and 20 with superview height of 70 . Alternatively you may use the conception of spacer views - an invisible UIView instance that is used just for layout adjusting, which is absolutely normal way of doing layout. In iOS9 Apple introduce new UILayoutGuide class which basically do the same thing, but does not consume any resources, like layers etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM