Using Auto Layout to have UILabel and UITextField next to each other(使用自动布局使 UILabel 和 UITextField 彼此相邻)
问题描述
我正在尝试将 UILabel 实例标签放置在 UITextField 实例文本字段旁边,就像在 iOS 设置对话框中所做的那样.我在 Florian Kuglers FLKAutoLayout 扩展的帮助下使用自动布局和约束(),解决方法是将标签的水平内容拥抱优先级设置为更高的值.
[self.label setContentHuggingPriority:500 forAxis:UILayoutConstraintAxisHorizontal];
那么即使输入较大的值也会让标签保持与其内容一样的宽度!
解决方案不是优先添加宽度约束,而是为 UIView 的固有内容大小设置 Compression Resistance 和 Content Hugging 属性.
I am trying to position a UILabel instance label next to a UITextField instance textfield like done in the iOS Settings dialogs. I'm using Auto Layout and constraints with the help of Florian Kuglers FLKAutoLayout extensions (https://github.com/dkduck/FLKAutoLayout).
When I set only a leading constraint for the label and a space constraint between label and textfield, the label and textfield widths are adjusted to their content. (bottom picture)
But when I set also a trailing constraint for the textfield, only textfields width is adjusted to its content, but label is stretched. (top picture)
I want to behave the opposite around, so that the textfield will be stretched and the label is adjusted to its content. Why does iOS decide to stretch the label instead of the textfield?
[self addSubview:self.label];
[self addSubview:self.textField];
[self.label alignLeadingEdgeWithView:self predicate:@"10"];
[self.textField constrainLeadingSpaceToView:self.label predicate:@"10"];
// difference between top and bottom pciture
// [self.textField alignTrailingEdgeWithView:self predicate:@"-25"];
EDITED: So after the comment of Rahul I played with width and priorities. Adding the following width constraint lead into the somewhat wrong direction, because of entering some very long value, the label was resized too small.
[self.label constrainWidth:@"0@1"];
So I finally read up on "Compression Resistance and Content Hugging" (http://www.objc.io/issue-3/advanced-auto-layout-toolbox.html) and the solution is to set the Horizontal Content Hugging priority of the label to a higher value.
[self.label setContentHuggingPriority:500 forAxis:UILayoutConstraintAxisHorizontal];
Then even entering big values will let the label stay as width as its content!
Solution is not adding a width constraint with priority, but to set Compression Resistance and Content Hugging properties for the intrinsic content size of the UIViews.
这篇关于使用自动布局使 UILabel 和 UITextField 彼此相邻的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用自动布局使 UILabel 和 UITextField 彼此相邻
基础教程推荐
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01