我在代码而不是 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 号是推荐的方式吗?我读过设置框架在自动布局世界中是一个普通的否?