使用自动布局水平对齐UIButtons(以编程方式)

时间:2015-09-18 02:02:36

标签: ios objective-c autolayout

我正试图水平放置2个UIButtons但没有运气

  1. 我正在以编程方式使用自动布局约束。
  2. 我不想把它们放在一个容器中,并将中心对准那个容器。

    @Autowired
    @Qualifier("userAccountService")
    IService<UserAccount> service;
    
    @Override
    public IService<UserAccount> getService() {
        return service;
    }
    
    @RequestMapping(value="/login", method=RequestMethod.POST)
    public @ResponseBody UserAccount login( String username, String password ){
        UserAccount userAccount = ((UserAccountService)service).loadUserByUsername(username);
        return userAccount;
    }
    
    @Secured("ADMIN_ROLE")
    @RequestMapping(value="/test", method=RequestMethod.POST)
    public @ResponseBody String test(){
        return "test...";
    }
    
    @RequestMapping(value="/denied", method=RequestMethod.POST)
    public @ResponseBody String denied(){
        return "denied...";
    }
    
  3. 第二个按钮从第一个结尾处开始,但是在下一行,而不是相同的。

1 个答案:

答案 0 :(得分:2)

我已经尝试过你的代码,但它已经崩溃了,所以根据你的问题你只需要写下面的代码。

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]];

结果:

enter image description here

希望它能帮助您解决问题。如果有任何疑问,请告诉我。