自製搜尋框時,如果直接讓文字貼齊左邊界,視覺上會顯得緊繃。解法是把左內距撐開一點,讓光標與提示文字都往右移。
#import <UIKit/UIKit.h> @interface SearchBar : UITextField @property (nonatomic, strong) UIButton *button; + (instancetype)searchBar; @end
#import "SearchBar.h"
@implementation SearchBar
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.font = [UIFont systemFontOfSize:15];
self.placeholder = @" 輸入品種關鍵字";
// 邊框與圓角
self.borderStyle = UITextBorderStyleNone;
self.layer.cornerRadius = 15.0f;
self.layer.masksToBounds = YES;
self.layer.borderColor = [[UIColor colorWithRed:224/255.0
green:243/255.0
blue:223/255.0
alpha:1.0] CGColor];
self.layer.borderWidth = 2.0f;
// 右側的搜尋按鈕
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 30)];
[button setBackgroundImage:[UIImage imageNamed:@"seachBar_rightView"]
forState:UIControlStateNormal];
[button setTitle:@"搜索" forState:UIControlStateNormal];
[button setTitleColor:[UIColor colorWithRed:119/255.0
green:166/255.0
blue:16/255.0
alpha:1.0]
forState:UIControlStateNormal];
button.titleLabel.font = [UIFont systemFontOfSize:18.0];
self.rightView = button;
self.rightViewMode = UITextFieldViewModeAlways;
// 關鍵:用 leftView 撐出左內距,讓光標往後移 10pt
self.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 0)];
self.leftViewMode = UITextFieldViewModeAlways;
}
return self;
}
+ (instancetype)searchBar {
return [[self alloc] init];
}
@end
UITextField 的 leftView 不一定是圖示,它可以是一個空的透明 view。只要給它足夠的寬度並設為 Always,系統就會在文字區域左側保留這段空白,光標與 placeholder 自然被往右推。
// 讓光標位置往後移 10pt textField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 0)]; textField.leftViewMode = UITextFieldViewModeAlways;
若只是單純想加內距,也可以實作 UITextField 的 textRectForBounds: 與 editingRectForBounds:(記得用 CGRectInset 或修改 origin.x),或直接使用 UIView.animate 搭配 contentInset。不過 leftView 的寫法最簡短,也不需要覆寫任何方法。
另外提醒,範例中 button.titleLabel.textColor 連續設了兩次(第二次覆蓋第一次),實作時應改用 setTitleColor:forState:,否則顏色不會生效。
以上示範了自訂 searchBar 並透過 leftView 調整光標初始位置的做法。這個技巧同樣適用於任何需要內距的 UITextField 場景。若有疑問歡迎留言,我會盡快回覆。