回答在座的一個老問題,但我用這一個我最近掙扎,發現了一些不足之處與其他答案的情況下,我試圖解決的問題。這裏是我在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]的寬度,但似乎只能在運行時訪問,並且不允許項目編譯。在任何情況下,這應該是您需要的良好開端
的權利雨燕3.0的版本:[發佈7203924(https://stackoverflow.com/a/44621016/7203924) – 2017-06-19 02:03:43