iOS UITextField文本缩进

1.缩进

思路:把UITextField的leftView、rightView当做填充位置,变相的实现文字偏移。

// 左边缩进(kTextIndent为缩进距离)
        UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kTextIndent, 0)];
        leftView.backgroundColor = [UIColor clearColor];
        // 保证点击缩进的view,也可以调出光标
        leftView.userInteractionEnabled = NO;
        textField.leftView = leftView;
        textField.leftViewMode = UITextFieldViewModeAlways;
        // 右边缩进
        UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kTextIndent + kCancelButtonWH + 17, kTextFieldHeight)];
        rightView.userInteractionEnabled = NO;
        rightView.backgroundColor = [UIColor clearColor];
        textField.rightView = rightView;
        textField.rightViewMode = UITextFieldViewModeAlways;
        // 右边 “x” 按钮(leftView和rightView上还可以添加图片、按钮等)
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
        [rightView addSubview:button];
        self.userNameRightBtn = button;

2.placeholder更换颜色

textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入账号密码" attributes:@{NSForegroundColorAttributeName:[UIColor redColor]}];

你可能感兴趣的:(iOS UITextField文本缩进)