OGeek|极客世界-中国程序员成长平台

标题: ios - 如何在Objective c中以编程方式在UIView中放置2个UIButton,宽度相等? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 10:14
标题: ios - 如何在Objective c中以编程方式在UIView中放置2个UIButton,宽度相等?

我使用了这段代码(在 UIView 类中)。

- (void)setup {

    self.backgroundColor = [UIColor colorWithWhite:0.12f alpha:1.0f];

    _doneTextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _doneTextButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [_doneTextButton setTitle"Save"  forState:UIControlStateNormal];
    [_doneTextButton setTitleColor:CODE_A_COLOR forState:UIControlStateNormal];

     [_doneTextButton setBackgroundColor:CODE_6_COLOR] ;
    [_doneTextButton.titleLabel setFont:[FontManager getOpenSansBoldFontWithSize:16]];
    [_doneTextButton addTarget:self actionselector(buttonTapped forControlEvents:UIControlEventTouchUpInside];

    [self addSubview:_doneTextButton];
}

我得到这个输出(角落的按钮)。

enter image description here

我希望这个“取消”和“保存”按钮完全适合 UIView

enter image description here

我正在使用第三方库。并且不知道直接逻辑不起作用。如何设置两个按钮的框架?期待自动布局代码。提前致谢。



Best Answer-推荐答案


您可以将按钮的框架设置为self.view.frame.size.width/2,然后您可以通过取第一个按钮的端点来设置第二个按钮的框架

-(void)setup
{
btnSave = [UIButton buttonWithType:UIButtonTypeCustom];
btnCancel = [UIButton buttonWithType:UIButtonTypeCustom];

btnSave.frame = CGRectMake(0, self.view.frame.size.height-30, self.view.frame.size.width/2, 30);

btnCancel.frame = CGRectMake(btnSave.frame.origin.x+btnSave.frame.size.width+5,  self.view.frame.size.height-30, btnSave.frame.size.width, 30);

btnSave.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
[btnSave setTitle"Save"  forState:UIControlStateNormal];
[btnSave setBackgroundColor:[UIColor blackColor]] ;
[self.view addSubview:btnSave];

btnCancel.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
[btnCancel setTitle"Cancel"  forState:UIControlStateNormal];
[btnCancel setBackgroundColor:[UIColor blackColor]] ;
[self.view addSubview:btnCancel];

}

关于ios - 如何在Objective c中以编程方式在UIView中放置2个UIButton,宽度相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34871812/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4