如何在布局中以编程方式对齐2个uibuttons?

时间:2014-08-27 11:45:30

标签: constraints uialertview nslayoutconstraint

我使用KLCPopup库在我的应用中显示弹出窗口。 我必须在这个弹出窗口的底部水平添加2个按钮,就像标准的iOS UIAlerView一样。我不能水平对齐这两个按钮。 以下是我想要的结果

The result I want

但这是我的结果: The only way I could find to add this 2 buttons

以下是我用来创建此弹出窗口的代码:

UIView* contentView = [[UIView alloc] init];
contentView.translatesAutoresizingMaskIntoConstraints = NO;

UILabel* dismissLabel = [[UILabel alloc] init];
dismissLabel.translatesAutoresizingMaskIntoConstraints = NO;
dismissLabel.numberOfLines = 0;
[dismissLabel setTextAlignment:NSTextAlignmentCenter];
dismissLabel.lineBreakMode = NSLineBreakByWordWrapping;
dismissLabel.preferredMaxLayoutWidth = 200;

UIButton* dismissButton = [UIButton buttonWithType:UIButtonTypeCustom];
dismissButton.translatesAutoresizingMaskIntoConstraints = NO;
dismissButton.contentEdgeInsets = UIEdgeInsetsMake(10, 20, 10, 20);

[contentView addSubview:dismissLabel];
[contentView addSubview:dismissButton];

UIButton* cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
cancelButton.translatesAutoresizingMaskIntoConstraints = NO;
cancelButton.contentEdgeInsets = UIEdgeInsetsMake(10, 20, 10, 20);

[contentView addSubview:cancelButton];

NSDictionary* views = NSDictionaryOfVariableBindings(contentView, dismissButton, cancelButton, dismissLabel);

[contentView addConstraints:
 [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(16)-[dismissLabel]-(16)-[dismissButton]-(16)-[cancelButton]-(16)-|"
                                         options:NSLayoutFormatAlignAllCenterX
                                         metrics:nil
                                           views:views]];

[contentView addConstraints:
 [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(18)-[dismissLabel]-(18)-|"
                                         options:0
                                         metrics:nil
                                           views:views]];

// Show in popup
KLCPopupLayout layout = KLCPopupLayoutMake(KLCPopupHorizontalLayoutCenter,
                                           KLCPopupVerticalLayoutCenter);

KLCPopup* popup = [KLCPopup popupWithContentView:contentView
                                        showType:KLCPopupShowTypeFadeIn
                                     dismissType:KLCPopupDismissTypeGrowOut
                                        maskType:KLCPopupMaskTypeDimmed
                        dismissOnBackgroundTouch:NO
                           dismissOnContentTouch:NO];

[popup showWithLayout:layout];

我认为我的代码问题是约束。我尝试了很多可能性,但我找不到正确的方法。

任何建议都会有所帮助!

由于

1 个答案:

答案 0 :(得分:1)

您已将所有三个视图添加到垂直约束中,这就是为什么它们都是一个接一个的原因。做这样的事情:

V:|-16-[dismissLabel]
V:|-80-[dismissButton]
V:|-80-[cancelButton]
H:|-18-[dismissLabel]-18-|
H:[dismissButton(50)]-100-[cancelButton(50)]

我没有测试过,但是这样的东西可以运行。您可能必须修改最后一个H值,或者可能为其添加居中选项。可能有更好的方法可以将这些东西分组,但这也应该有效。