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

标签 ios objective-c uitoolbar 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 种方法是推荐的方法吗?我读过设置框架在自动布局世界中是一个简单的“否”?

最佳答案

设置 View 的框架是可以的,如果 View 有 translatesAutoresizingMaskToConstraints设置为YES 。许多系统 View 都使用此设置。此设置是您在代码中创建的 View 的默认设置。从 Nib (或 Storyboard)加载的 View 将其设置为 NO如果 Nib 设置为使用自动布局。

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

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

关于ios - 在代码中使用自动布局调整 UIButtons 大小的最佳实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17372967/

相关文章:

ios - NSMutableArray removeObjectAtIndex 错误

ios - 单击按钮时在 tableViewCell 中配置数据

ios - 底部布局指南防止与与 uitabbar 交换的 uitoolbar 交互

ios - 如何在 View Controller 之间传递参数

objective-c - 简单 iPhone 应用程序中的 SIGABRT

ios - 如何使用 shouldPerformSegueWithIdentifier 在正确的时间显示 HUD?

ios - 顶部工具栏和导航栏常用模糊效果

ios - 顶部/底部位置的UIToolbar外观界面

ios - 如何在 Xcode 中本地化 xcassets 文件夹中的图像

ios - 屏幕的实际尺寸比我看到的要大