将左边距添加到UITextField
我想把UITextField
文本的左边距设置为10像素。 什么是最好的方法来做到这一点?
正如我在前面的评论中所解释的,在这种情况下,最好的解决scheme是扩展UITextField类而不是使用类别,所以你可以明确地在所需的文本字段上使用它。
#import <UIKit/UIKit.h> @interface MYTextField : UITextField @end @implementation MYTextField - (CGRect)textRectForBounds:(CGRect)bounds { int margin = 10; CGRect inset = CGRectMake(bounds.origin.x + margin, bounds.origin.y, bounds.size.width - margin, bounds.size.height); return inset; } - (CGRect)editingRectForBounds:(CGRect)bounds { int margin = 10; CGRect inset = CGRectMake(bounds.origin.x + margin, bounds.origin.y, bounds.size.width - margin, bounds.size.height); return inset; } @end
类别旨在将新function添加到现有类,而不是覆盖现有方法。
你可以通过扩展UITextField
类并重写两个方法来实现:
- (CGRect)textRectForBounds:(CGRect)bounds; - (CGRect)editingRectForBounds:(CGRect)bounds;
这里是代码:
MYTextField.h
的接口
@interface MYTextField : UITextField @end
它在MYTextField.m
实现
@implementation MYTextField static CGFloat leftMargin = 28; - (CGRect)textRectForBounds:(CGRect)bounds { bounds.origin.x += leftMargin; return bounds; } - (CGRect)editingRectForBounds:(CGRect)bounds { bounds.origin.x += leftMargin; return bounds; } @end
UITextField * textField = [[UITextField alloc]init]; [textField setDelegate:self]; [textField setFrame:CGRectMake(170,112,140,25)]; [textField setBorderStyle:UITextBorderStyleNone]; [textField setBackgroundColor:[UIColor clearColor]]; [self.View addSubview:noofChildTField]; UIView *paddingView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 20)] autorelease]; textField.leftView = paddingView; textField.leftViewMode = UITextFieldViewModeAlways;
试试这个代码
对于Swift 3:
创buildUITextField
的出口,例如usernameTextField。 然后在viewDidLoad()
写下下面的代码
let paddingView : UIView = UIView(frame: CGRect(x: 0, y: 0, width: 5, height: 20)) usernameTextField.leftView = paddingView usernameTextField.leftViewMode = .always
如果需要更多的空间,将width: 5
更改为更大的值。
我希望在财产检查员看到一个IB的设置来调整这个值。 原来我已经无意中将alignment和边框样式设置为与左侧填充混淆的值。
你不会认为select左alignment和没有边界会是一个大问题,但是它使得这些单词基本上重叠或者直接到达框的边缘,而且看起来不正确。
坏:
好:
修正了它对我来说。 希望这可以帮助别人。
我已经达到几乎覆盖- (CGRect)textRectForBounds:(CGRect)bounds
。 现在的问题是,当TextField进入编辑模式,他们的左边距重置为零…….
@implementation UITextField(UITextFieldCatagory) - (CGRect)textRectForBounds:(CGRect)bounds { CGRect theRect=CGRectMake(bounds.origin.x+10, bounds.origin.y, bounds.size.width-10, bounds.size.height); return theRect; }
你可以试试这个
TextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; TextField.textAlignment = UITextAlignmentCenter;