UITextField设置内边距的三种方式

1、利用UITextField的属性leftView,创建一个宽为5,高为20的View设置为UITextField的leftView,这样视觉上就会有5像素的左边距

1
2
3
UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 20)];
textField.leftView = paddingView;
textField.leftViewMode = UITextFieldViewModeAlways;

2、MAC OS中以及iOS7.0以前可以使用如下方法设置

1
2
3
4
[self.yourTextField setValue:[NSNumber numberWithInt:5] forKey:@"_paddingTop"];
[self.yourTextField setValue:[NSNumber numberWithInt:5] forKey:@"_paddingLeft"];
[self.yourTextField setValue:[NSNumber numberWithInt:5] forKey:@"_paddingBottom"];
[self.yourTextField setValue:[NSNumber numberWithInt:5] forKey:@"_paddingRight"];

3、自定义一个TextField,实现如下两个方法

1
2
3
4
5
6
7
8
9
10
11
//控制placeHolder 的位置,左右缩 8px
- (CGRect)textRectForBounds:(CGRect)bounds
{
    return CGRectInset(bounds , 8 , 0 );
}
 
// 控制文本的位置,左右缩 8px
- (CGRect)editingRectForBounds:(CGRect)bounds
{
    return CGRectInset(bounds , 8 , 0 );
}

Leave a Reply