UITextField的占位符边距和初始游标边距

时间:2016-07-21 09:07:54

标签: ios objective-c swift

我有一个带有一些占位符的文本字段。我想从左边给出20PX的保证金来显示占位符,并且还想在同一边缘设置初始切割器。

4 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:3)

您必须创建UITextField的子类并覆盖textRectForBounds:editingRectForBounds:方法以返回插入的rect。

你可以做类似的事情:

func textRectForBounds(bounds: CGRect) -> CGRect {
    return adjustBounds(bounds)
}

func editingRectForBounds(bounds: CGRect) -> CGRect {
    return adjustBounds(bounds)
}

private func adjustBounds(bounds: CGRect) -> CGRect {
    var newBounds = bounds
    newBounds.origin.x += 20
    newBounds.size.width -= 20
    return newBounds
}

// If you need to place the UITextField placeholder in the initial 20px, 
// you have to override this method as well to provide the right rect.
func placeholderRect(forBounds bounds: CGRect) -> CGRect {
    var newBounds = bounds
    newBounds.origin.x = 0
    newBounds.size.width = 20
    return newBounds
}

参考:Text inset for UITextField?

答案 2 :(得分:1)

您可以创建自定义UITextField。 实现以下方法并根据需要设置Inset值

// placeholder position
- (CGRect)textRectForBounds:(CGRect)bounds {
    return CGRectInset(bounds, 10, 10);
}

// text position
- (CGRect)editingRectForBounds:(CGRect)bounds {
    return CGRectInset(bounds, 10, 0);
}

答案 3 :(得分:1)

占位符位置

  - (CGRect)textRectForBounds:(CGRect)bounds {
         return CGRectInset( self.bounds , margin position , margin position );
    }

对于文字位置

    - (CGRect)editingRectForBounds:(CGRect)bounds {
         return CGRectInset( self.bounds , margin position ,margin position );
    }