設定 textField.background = [UIImage imageNamed:@"bg"] 後,圖片無法撐滿輸入框,文字顯示在圖片邊界外,視覺錯位。
background 屬性僅繪製圖片,不自動縮放填滿 bounds。UITextField 內部有固定的 textRect/editingRect,預設留白導致文字超出背景圖可視區。// 建立 10pt 左側間距
UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 20)];
textField.leftView = paddingView;
textField.leftViewMode = UITextFieldViewModeAlways;
// 同理可加 rightView 控制右側間距
UIView *rightPadding = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 20)];
textField.rightView = rightPadding;
textField.rightViewMode = UITextFieldViewModeAlways;
@interface InsetTextField : UITextField
@property (nonatomic) UIEdgeInsets textInsets;
@end
@implementation InsetTextField
- (CGRect)textRectForBounds:(CGRect)bounds {
return UIEdgeInsetsInsetRect(bounds, self.textInsets);
}
- (CGRect)editingRectForBounds:(CGRect)bounds {
return UIEdgeInsetsInsetRect(bounds, self.textInsets);
}
- (CGRect)placeholderRectForBounds:(CGRect)bounds {
return UIEdgeInsetsInsetRect(bounds, self.textInsets);
}
@end
// 使用
InsetTextField *tf = [[InsetTextField alloc] initWithFrame:frame];
tf.textInsets = UIEdgeInsetsMake(0, 12, 0, 12); // 上左下右
tf.background = [UIImage imageNamed:@"bg"];
UIImageView *bgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg"]];
bgView.frame = textField.bounds;
bgView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
bgView.contentMode = UIViewContentModeScaleToFill;
[textField insertSubview:bgView atIndex:0]; // 放在最底層
textField.background = nil; // 清除原背景
textField.borderStyle = UITextBorderStyleNone;
@2x/@3x 並啟用 resizableImageWithCapInsets 九宮格拉伸,避免失真。