我想将UITextField添加到UITooolbar并让UITextField根据需要扩展其宽度以填充该区域,就像UIBarButtonSystemItemFlexibleSpace一样.
下面是一个关于我如何在视图控制器中正常设置工具栏项的片段...
// two UIBarButtonItems
UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:nil];
UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStylePlain target:nil action:nil];
// the UIBarButtonItem with a UITextField as custom view
UITextField *textField = [[UITextField alloc] init];
textField.borderStyle = UITextBorderStyleRoundedRect;
UIBarButtonItem *text = [[UIBarButtonItem alloc] initWithCustomView:textField];
[self setToolbarItems:@[left, text, right]];
Run Code Online (Sandbox Code Playgroud)
......然后会出现这样的情况.
在iOS 11之前,我对UIToolbar进行了细分,并使用layoutSubviews方法获取CGRectGetWidth(itemView.frame)所有"非灵活"项目的width(),并计算textfields视图框架的可用宽度.在iOS 11中,Apple更改为自动布局所有条形,如WWDC2017会话204中所述,现在该CGRectGetWidth(itemView.frame)方式将无法提供有效宽度,直到视图可见,这也是在iOS 11 UIBarButtonItem图像中指出的未调整尺寸.
我现在如何使用约束和自动布局添加灵活大小的UIBarButtonItems和customViews,这将扩展以填充两个项目之间的完整空闲区域?
编辑1:
如果我只添加文本字段,项目将按预期扩展其宽度.
编辑2:
直接在UIToolbar中使用约束似乎是不可能的,因为项目视图不存在(直到它们被放置?)或没有超视图.
UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:nil];
UIView …Run Code Online (Sandbox Code Playgroud)