在这里回答一个老问题,但我最近自己也在努力解决这个问题,并发现其他答案对于我试图解决的情况存在一些缺点。这是我在 UISearchBar 的子类中所做的:
首先添加一个 UIButton 属性(这里是“selectButton”)。然后重写 initWithFrame 方法并执行类似于以下的操作:
-(id)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame])
{
self.selectButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
self.selectButton.contentEdgeInsets = (UIEdgeInsets){.left=4,.right=4};
[self.selectButton addTarget:self action:@selector(pressedButton:) forControlEvents:UIControlEventTouchUpInside];
self.selectButton.titleLabel.numberOfLines = 1;
self.selectButton.titleLabel.adjustsFontSizeToFitWidth = YES;
self.selectButton.titleLabel.lineBreakMode = UILineBreakModeClip;
[self addSubview:self.selectButton];
[self.selectButton setFrame:CGRectMake(5, 6, 60, 31)];
}
return self;
}
现在您要覆盖布局子视图方法以将搜索栏调整为适当的宽度,具体取决于取消按钮是否显示。应该是这样的:
-(void)layoutSubviews
{
[super layoutSubviews];
float cancelButtonWidth = 65.0;
UITextField *searchField = [self.subviews objectAtIndex:1];
if (self.showsCancelButton == YES)
[searchField setFrame:CGRectMake(70, 6, self.frame.size.width - 70 - cancelButtonWidth, 31)];
else
[searchField setFrame:CGRectMake(70, 6, self.frame.size.width - 70, 31)];
}
请注意,在上述方法中,我为 cancelButtonWidth 添加了一个常量。我尝试添加代码以从 [self cancelButton] 获取宽度,但这似乎只能在运行时访问并且不允许项目编译。无论如何,这应该是您需要的一个好的开始