使UIView和内容展开以使用自动布局填充UIToolbar中的可用水平空间

我有一个UIBarButtonItem和一个包含两个UITextField控件的UIView ,都在UIToolbar

这是我的故事板的截图: http : //i.8px.co/x8eC.png 。

我想创建类似的东西: http : //i.8px.co/1hvY.png 。

我正在尝试使UIView及其子项扩展以使用自动布局填充UIToolbar的可用水平空间。 我不知道如何完成我想要的。

我为UIView实验了一个肮脏的解决方案,并且能够正确地确定它的大小。

 view.width = toolBar.frame.width - button.width // where view is the UIView, toolBar is the UIToolBar, and button is the UIBarButtonItem 

我不相信这很优雅。 这是以编程方式完成的, UIView不符合标准的UIToolbar边距,并且该解决方案不适用于UITextFields

我担心你必须以编程方式执行此操作。

尝试这个 :

  self.toolBarview.frame = (CGRect) {.origin = self.toolBarview.frame.origin.x, self.toolBarview.frame.origin.y, .size = [UIScreen mainScreen].bounds.size.width - self.barButton.width - 40, self.toolBarview.frame.size.height}; 

这里的toolBarview是UIView ,它有2个UITextField 。 40是需要减去以给出填充的缓冲区值。

/ *编辑* /

您应该为UITextField提供适当的约束 ,如下所示:

文本域约束

“我正在努力让UIView和它的孩子们扩展来填充UIToolbar中可用的自动布局的水平空间”你做不到。 UIView位于UIBarButtonItem中,而UIBarButtonItem 不是视图 。 所以你不能在它上面使用自动布局。 您必须手动设置其宽度。

你可以用很多方式做到这一点,

做这些约束

在此处输入图像描述

在此处输入图像描述

然后创建一个UITextField的子类,并执行此代码

 class CustomTextField: UITextField { override func textRectForBounds(bounds: CGRect) -> CGRect { return CGRectInset(CGRectMake(65, 0, bounds.size.width-65, bounds.size.height) , 0 , 0 ) } override func editingRectForBounds(bounds: CGRect) -> CGRect { return CGRectInset(CGRectMake(65, 0, bounds.size.width-65, bounds.size.height) , 0 , 0 ) } } 

在storyboard / xib中,将textField连接到CustomTextField

在此处输入图像描述

为2个textField创建sockets

 @IBOutlet weak var textField1: CustomTextField! @IBOutlet weak var textField2: CustomTextField! 

在viewDidLoad()方法中,

  var label1 : UILabel = UILabel(frame: CGRectMake(5, (textField1.frame.height/2)-15, 100, 30)) label1.textColor = UIColor.lightGrayColor(); label1.text = "From:" var label2 : UILabel = UILabel(frame: CGRectMake(5, (textField1.frame.height/2)-15, 100, 30)) label2.textColor = UIColor.lightGrayColor(); label2.text = "To:" textField1.addSubview(label1) textField2.addSubview(label2) 

然后你会得到像…那样的输出

在此处输入图像描述