【发布时间】:2015-07-18 05:57:15
【问题描述】:
我正在通过代码学习自动布局。为了我的学习目的,我正在使用自动布局做示例应用程序。在我的示例应用程序中,我决定将文本字段保持在距上边距 20 点以下。这是代码
#import "SampleViewController.h"
@interface SampleViewController (){
UITextField *username;
}
@end
@implementation SampleViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.edgesForExtendedLayout = UIRectEdgeNone;
[self prepareViews];
}
-(void)prepareViews{
username = [[UITextField alloc]init];
username.placeholder = @"Username";
[username setBorderStyle:UITextBorderStyleRoundedRect];
username.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:username];
[self prepareConstraint];
}
-(void)prepareConstraint{
NSLayoutConstraint *constraint = [NSLayoutConstraint
constraintWithItem:username
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterX
multiplier:1.0
constant:0];
[self.view addConstraint:constraint];
constraint = [NSLayoutConstraint
constraintWithItem:username
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0
constant:250];
[self.view addConstraint:constraint];
constraint = [NSLayoutConstraint
constraintWithItem:username
attribute:NSLayoutAttributeTopMargin
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeTopMargin
multiplier:1.0
constant:20];
[self.view addConstraint:constraint];
}
@end
当我在 iphone 4(iOS 7.1) 上运行此代码时,我得到了这样的输出 然后,当我在 iphone 5S(iOS 8.4)上运行此代码时,我得到了这样的输出
伙计们,我不知道我在哪里犯了错误。请指出我在哪里犯了错误。当我在 iphone 4 (iOS 7.1) 上运行此代码时,我收到了这个警告。
无法同时满足约束。可能至少有一个 以下列表中的约束是您不想要的。尝试 这个:(1)查看每个约束并尝试找出你 不要期待; (2) 找到添加了不需要的约束的代码或 约束并修复它。 (注:如果你看到 NSAutoresizingMaskLayoutConstraints 你不明白的,参考 到 UIView 属性的文档 translatesAutoresizingMaskIntoConstraints) ( "<0x14dcac70 h:>0x14dcac70>
<0x14dcac70 h:>0x14dcac70>
标签: ios objective-c iphone uiview