在实际开发中如果UITextView UITextField
靠屏幕边界,会影响美观和用户交互体验,所以常常需要设置内容的insets
,虽然老B都有所了解如何设置,不过今天在群里有人问及,所以总结了下。
- UITextView
UIEdgeInsets insets = textView.contentInset;
textView.contentInset = UIEdgeInsetsMake(insets.top, 10.0, insets.bottom, insets.right);
- UITextField 没有
contentInset
属性,不过有几种方法可以实现该效果。
方法一重写 -textRectForBounds
和 -editingRectForBounds
// placeholder position
- (CGRect)textRectForBounds:(CGRect)bounds {
return CGRectInset(bounds, 10.0, 10.0);
}
// text position
- (CGRect)editingRectForBounds:(CGRect)bounds {
return CGRectInset(bounds, 10.0, 10.0);
}
方法二
textField.layer.sublayerTransform = CATransform3DMakeTranslation(10, 0, 0);
方法三
UItextField *textField = [[UITextField alloc] initWithFrame:...];
UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, textField.frame.size.height)];
leftView.backgroundColor = textField.backgroundColor;
textField.leftView = leftView;
textField.leftViewMode = UITextFieldViewModeAlways;