iOS UITextField 编辑时文本偏移问题

1.在cell中添加UITextField,在编辑的时候总是出现文本偏移问题,编辑结束时回复正常,解决方式如下:

(1)代码创建UITextField,并添加上去,设置textField的一些属性:

- (UITextField *)textField{

    if (_textField == nil) {

        _textField = [UITextField new];
        _textField.borderStyle = UITextBorderStyleNone;
        _textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        _textField.textAlignment = NSTextAlignmentLeft;
        _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _textField.tintColor = [UIColor redColor];
        _textField.font = GXFont(16);
        _textField.returnKeyType = UIReturnKeyDone;
        _textField.delegate = self;
    }
    return _textField;
}
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self.contentView addSubview:self.textField];
    }
    return self;
}

- (void)layoutSubviews{
    [super layoutSubviews];

    self.textField.frame = (CGRect){{kDefaultSpace, 0},{GXScreenWidth-2*kDefaultSpace, CGRectGetHeight(self.frame)}};
}

(2)xib创建,并拉线成属性:

iOS UITextField 编辑时文本偏移问题_第1张图片

代码中设置属性:


    self.textFidle.textAlignment = NSTextAlignmentLeft;
    self.textFidle.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    self.textFidle.borderStyle = UITextBorderStyleNone;
    self.textFidle.backgroundColor = [UIColor lightGrayColor];

设置成功,如果还不成功的话,就要吧各个属性都测试一下,

注意:self.textFidle.clipsToBounds = YES;这句话好像对偏移有影响,大家注意一下,我测试的是如果在上面的属性基础上加上这句话,文本就会偏移,去掉就没问题.

你可能感兴趣的:(Xcode-小知识点)