在實(shí)際開發(fā)中如果UITextView UITextField靠屏幕邊界,會(huì)影響美觀和用戶交互體驗(yàn),所以常常需要設(shè)置內(nèi)容的insets,雖然老B都有所了解如何設(shè)置,不過今天在群里有人問及,所以總結(jié)了下。
- UITextView
UIEdgeInsets insets = textView.contentInset;
textView.contentInset = UIEdgeInsetsMake(insets.top, 10.0, insets.bottom, insets.right);
- UITextField 沒有
contentInset屬性,不過有幾種方法可以實(shí)現(xiàn)該效果。
方法一重寫 -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;