【发布时间】:2013-03-26 11:46:02
【问题描述】:
我正在尝试使用约束来制作布局,但我有许多带有内部嵌套子视图的自定义控件。我正在将约束添加到顶视图(CustomView),但它没有正确布置子视图。
例如。我有 TextFieldWithLabel 类,它在 UITextField 的顶部和下方显示标签,我正在创建 TextFieldWithLabel 的实例并添加到带有约束的超级视图。
但它没有按预期显示结果。 虽然它可见但没有放在我想要的位置。为此,我不想更改整个 TextFieldWithLabel 类的敌人自动布局。
请帮忙!
usernameTextField = [[TextFieldWithLabel alloc] initWithFrame:CGRectMake(0, 0, 100, 50) name:@"UserName"];
[usernameTextField setTranslatesAutoresizingMaskIntoConstraints:NO];
[superview addSubview:usernameTextField];
NSLayoutConstraint* myConstraint = [NSLayoutConstraint constraintWithItem:usernameTextField
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:superview
attribute:NSLayoutAttributeCenterY
multiplier:1
constant:0];
[superview addConstraint:myConstraint];
myConstraint = [NSLayoutConstraint constraintWithItem:usernameTextField
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:superview
attribute:NSLayoutAttributeCenterX
multiplier:1
constant:0];
[superview addConstraint:myConstraint];
屏幕截图: 这里它没有居中,而且文本字段 (RedColor) 也不能点击。标签和文本字段放置在 TextFieldWithLabel 内。 请注意:TextFieldWithLabel 是 ComponentView 的子类,而 ComponentView 是 UIView 的子类。所以我怀疑这可能是问题所在?我是否也需要自动布局 ComponentsView。
【问题讨论】:
-
请展示您是如何创建自定义控件的 - 它们是在代码中、在 xib 中、使用自动布局、弹簧和支柱制作的吗?还请附上屏幕截图,指出错误的布局在哪里。目前很难回答这个问题。
-
感谢回复,我正在代码中创建CustomView。
-
那么,您可以编辑问题以包含代码吗?
-
添加的代码请看一下
-
因此,您尝试将 textFieldWithLabel 置于超级视图的中心。它是什么样子的?是不是在正确的地方,但尺寸不对?
标签: ios constraints frame autolayout addsubview