Ios 使用自动布局水平对齐UI按钮(以编程方式)
我试图水平放置2个UIButton,但运气不好Ios 使用自动布局水平对齐UI按钮(以编程方式),ios,objective-c,autolayout,Ios,Objective C,Autolayout,我试图水平放置2个UIButton,但运气不好 我正在以编程方式使用自动布局约束 我不想把它们放在一个容器里,然后把中心对准那个容器 NSDictionary *metrics = @{@"kLeftPadding":@(kLeftPadding), @"kRightPadding":@(kRightPadding), @"kMiddlePadding":@(kMiddlePadding),
NSDictionary *metrics = @{@"kLeftPadding":@(kLeftPadding),
@"kRightPadding":@(kRightPadding),
@"kMiddlePadding":@(kMiddlePadding),
@"kBottomPadding":@(kBottomPadding)};
NSDictionary *constrainedViews = @{@"titleLabel": self.titleLabel,
@"btnToday" : self.btnToday,
@"btnPickaDay" : self.btnPickaDay,
@"dividerView" : dividerView};
NSArray *contraints = @[@"V:|-[titleLabel]-kBottomPadding-[btnToday(==40)]-[btnPickaDay(==btnToday)]-kBottomPadding-[dividerView]-0-|",
@"H:|-kLeftPadding-[titleLabel]-|",
@"H:|-kLeftPadding-[btnToday]-kMiddlePadding-[btnPickaDay(==btnToday)]-kRightPadding-|",
@"H:|-0-[dividerView]-0-|"];
第二个按钮从第一个结束的地方开始,但在下一行,不是在同一行。我尝试了你的代码,但它崩溃了,所以根据你的问题,你只需要写下面的代码
UILabel *lblText = [UILabel new];
[lblText setText:@"Some Title Text"];
[lblText setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addSubview:lblText];
UIButton *btnRed = [UIButton new];
[btnRed setBackgroundColor:[UIColor redColor]];
[btnRed setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addSubview:btnRed];
UIButton *btnGreen = [UIButton new];
[btnGreen setBackgroundColor:[UIColor greenColor]];
[btnGreen setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addSubview:btnGreen];
UIView *vwLine = [UIView new];
[vwLine setBackgroundColor:[UIColor blueColor]];
[vwLine setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addSubview:vwLine];
NSDictionary *dictViews = @{@"red":btnRed,@"green":btnGreen,
@"line":vwLine,@"lbl":lblText};
NSDictionary *dictMetrics = @{@"height":@(40),@"offset":@(-40)};
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-20-[red]-0-[green(==red)]-20-|" options:0 metrics:nil views:dictViews]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-20-[line]-20-|" options:0 metrics:nil views:dictViews]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-20-[lbl]-20-|" options:0 metrics:nil views:dictViews]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(height)-[lbl]-(height)-[red(height)]-(offset)-[green(==red)]-50-[line(2)]" options:0 metrics:dictMetrics views:dictViews]];
结果:
希望它能帮助你解决你的问题。如果还有任何查询,请告诉我。你能添加截图吗?你得到的和你想要的输出。@iOS_DK这里是@iOS_DK上面的链接是当前结果,这里是想要的输出:实际上我的截图是我不想要的输出,我想要这两个按钮对齐在这里你可以看到标题,两个按钮和一个分隔符,这两个按钮当前未对齐,它们与您的结果类似。[self.view addConstraints:[NSLAYOUTCONSTRAINTS WITH VISUALFORMAT:@“H:|-20-[红色]-0-[绿色(=红色)]-20-|”选项:0指标:无视图:dictViews];[self.view addConstraints:[NSLayoutConstraintsWithVisualFormat:@“V:|-0-[红色(高度)]-0-[绿色(=红色)]选项:0度量:dictMetrics视图:dictViews];上面的几行可能有助于让我对齐按钮,但除了标题和分隔符之外,还有一些混乱的地方,看起来很棒。谢谢+1