我在代码中使用自动布局而不是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 种方法是推荐的方法吗?我读过设置框架在自动布局世界中是一个简单的“否”?
最佳答案
设置 View 的框架是可以的,如果 View 有 translatesAutoresizingMaskToConstraints
设置为YES
。许多系统 View 都使用此设置。此设置是您在代码中创建的 View 的默认设置。从 Nib (或 Storyboard)加载的 View 将其设置为 NO
如果 Nib 设置为使用自动布局。
不要尝试在按钮和工具栏之间设置约束。工具栏不使用约束来布局其项目 View 。 (您可以通过在调试器中浏览 View 层次结构来看到这一点。)
刚刚设置addButton.frame.size
或addButton.bounds.size
到您希望按钮具有的大小,然后设置 addNewItemButton.width
为零。将项目宽度设置为零告诉工具栏使用按钮自己的大小。工具栏将使按钮垂直居中。如果要在按钮前添加水平间距,请插入另一个 UIBarButtonItem
类型为UIBarButtonSystemItemFixedSpace
.
关于ios - 在代码中使用自动布局调整 UIButtons 大小的最佳实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17372967/