当我尝试创建按钮组时,为什么按钮会折叠?

时间:2015-01-19 15:34:46

标签: ios objective-c

我试图横向创建UIButton组。

所以我创建了两个按钮并创建了一个包含它们的新视图。然后我添加约束以使其均匀地水平放置。

但是这两个UIButtons刚崩溃了。按钮的初始位置是相同的,但我认为不重要。

- (UIButton*) getButtonWithTitle: (NSString*) title
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(0, 80, 130.0, 40.0);

    button.layer.borderColor  = [UIColor blackColor].CGColor;
    button.layer.borderWidth  = 0.5f;
    button.layer.cornerRadius = 2.0f;

    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState: UIControlStateNormal];
    return button;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    UIButton *loginBtn    = [self getButtonWithTitle:@"Login"];
    UIButton *registerBtn = [self getButtonWithTitle:@"Register"];

    UIView *buttonGroup = [[UIView alloc] init];
    [buttonGroup setTranslatesAutoresizingMaskIntoConstraints:NO];
    [buttonGroup addSubview: loginBtn];
    [buttonGroup addSubview: registerBtn];
    [self.view addSubview: buttonGroup];

    NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(loginBtn, registerBtn, buttonGroup);
    [buttonGroup addConstraints:
     [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[loginBtn]-20-[registerBtn]-|"
                                             options:0 metrics:nil
                                               views:viewsDictionary
      ]];
}

修改

我关注deimus并删除了buttonGroup,但没有更改:

enter image description here

1 个答案:

答案 0 :(得分:1)

从此行中删除buttonGroup,然后重试。

NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(loginBtn, registerBtn, buttonGroup);

同时删除

button.frame = CGRectMake(0, 80, 130.0, 40.0);

当您选择使用AutoLayouting时,再也无法提供手动坐标