如何使用autolayout水平和垂直居中输入和按钮

时间:2015-12-19 23:48:45

标签: ios objective-c autolayout

我在我的ViewController中初始化文本输入和保存按钮,但它没有显示我想要的方式,如下面的屏幕截图所示。

我试图通过使用autolayout按照建议的here来解决这个问题,但它给了我一个错误

  

使用未声明的标识符cn

如何正确声明自动布局,这是以input_saveButton为中心的正确方法吗?

- (void)viewDidLoad {
    [super viewDidLoad];

    //Dem Input
    input = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 150, 40)];
    input.textColor = [UIColor blackColor];
    input.font = [UIFont fontWithName:@"Times-New-Roman" size:25];
    input.backgroundColor=[UIColor whiteColor];
    [input setBorderStyle:UITextBorderStyleLine];
    input.placeholder=@"Type words here...";

    //The Button
    _saveButton = [UIButton buttonWithType: UIButtonTypeRoundedRect];
    _saveButton.frame = CGRectMake(0, 0, 100, 18);
    [_saveButton setTitle:@"Save" forState:UIControlStateNormal];
    [_saveButton addTarget:self action:@selector(saveButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:input];
    [self.view addSubview:_saveButton];

    cn = [NSLayoutConstraint constraintWithItem:self.view
                                      attribute:NSLayoutAttributeHeight
                                      relatedBy:NSLayoutRelationEqual
                                         toItem:nil
                                      attribute:NSLayoutAttributeNotAnAttribute
                                     multiplier:1
                                       constant:200];
    [self.view addConstraint:cn];

    cn = [NSLayoutConstraint constraintWithItem:self.view
                                      attribute:NSLayoutAttributeWidth
                                      relatedBy:NSLayoutRelationEqual
                                         toItem:nil
                                      attribute:NSLayoutAttributeNotAnAttribute
                                     multiplier:1
                                       constant:200];
    [self.view addConstraint: cn];

}

enter image description here

0 个答案:

没有答案