在代码中使用自动布局调整UIButtons大小的最佳实践



我在代码中使用autolayout而不是IB向UIToolbar添加自定义按钮。我的问题是关于最佳实践。我是否使用以下代码来添加、设置和调整工具栏中的按钮大小:

(1)

//-------------------------------------------------------
// Toobar View
//-------------------------------------------------------
UIToolbar *toolbar = [UIToolbar new];
UIButton *addButton = [UIButton buttonWithType:UIButtonTypeCustom];
[addButton setImage:[UIImage imageNamed:@"add_normal"] forState:UIControlStateNormal];
[addButton setImage:[UIImage imageNamed:@"add_highlighted"] forState:UIControlStateHighlighted];
[addButton addTarget:self action:@selector(addItem:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *addNewItemButton = [[UIBarButtonItem new] initWithCustomView:addButton];
[toolbar setItems:[NSArray arrayWithObject:addNewItemButton] animated:NO];
// Add Views to superview
[superview addSubview:topbarView];
[superview addSubview:_tableView];
[superview addSubview:toolbar];
[toolbar addConstraints:[NSLayoutConstraint
                           constraintsWithVisualFormat:@"H:|-(10)-[addButton(39)]"
                           options:0
                           metrics:nil
                           views:viewsDictionary]];
[toolbar addConstraints:[NSLayoutConstraint
                            constraintsWithVisualFormat:@"V:|-(7)-[addButton(29)]"
                            options:0
                            metrics:nil
                            views:viewsDictionary]];

(2) 或者我可以使用不同的代码来调整按钮的大小吗

CGRect buttonFrame = addButton.frame;
buttonFrame.size = CGSizeMake(19, 19);
addButton.frame = buttonFrame;

那么,1号是推荐的方式吗?我读到设置框架是一个在自动布局世界中的一个明显的禁忌?

如果视图的translatesAutoresizingMaskToConstraints设置为YES,则可以设置视图的框架。许多系统视图都使用此设置。此设置是您在代码中创建的视图的默认设置。如果笔尖设置为使用自动布局,则从笔尖(或故事板)加载的视图将其设置为NO

不要试图在按钮和工具栏之间设置约束。工具栏不使用约束来布置其项目视图。(您可以通过在调试器中浏览视图层次结构来看到这一点。)

只需将addButton.frame.sizeaddButton.bounds.size设置为您想要的按钮大小,然后将addNewItemButton.width设置为零。将项目宽度设置为零告诉工具栏使用按钮自己的大小。工具栏将使按钮垂直居中。如果要在按钮前添加水平间距,请插入另一个类型为UIBarButtonSystemItemFixedSpaceUIBarButtonItem

最新更新