我想为我的UITextFields使用一个自定义背景。这很好,除了我必须使用UITextBorderStyleNone来使它看起来很漂亮。这将迫使文本保持在左边,没有任何填充。
我可以手动设置填充,使它看起来类似于UITextBorderStyleRoundedRect除了使用我的自定义背景图像?
我想为我的UITextFields使用一个自定义背景。这很好,除了我必须使用UITextBorderStyleNone来使它看起来很漂亮。这将迫使文本保持在左边,没有任何填充。
我可以手动设置填充,使它看起来类似于UITextBorderStyleRoundedRect除了使用我的自定义背景图像?
当前回答
Nate Flink的回答是我最喜欢的,但不要忘记左右观点。 例如UITextField子类:
override func rightViewRectForBounds(bounds: CGRect) -> CGRect {
let rightViewBounds = super.rightViewRectForBounds(bounds)
return CGRectMake(CGRectGetMinX(rightViewBounds) - 10, CGRectGetMinY(rightViewBounds), CGRectGetWidth(rightViewBounds), CGRectGetHeight(rightViewBounds))
}
上面的代码为UITextField的rightView设置了右填充。
其他回答
我发现使用不可编辑的UITextView并设置contenttoffset要容易得多
uiTextView.contentOffset = CGPointMake(8, 7);
下面是一个Swift代码,在UITextfield中提供填充
func txtPaddingVw(txt:UITextField) {
let paddingView = UIView(frame: CGRectMake(0, 0, 10, 10))
txt.leftViewMode = .Always
txt.leftView = paddingView
}
调用using
self.txtPaddingVw(txtPin)
textField.layer.borderWidth = 3;
将添加边框,这对我来说是填充。
另一个需要考虑的问题是,如果你在添加填充的地方有多个UITextField,就要为每个文本字段创建一个单独的UIView——因为它们不能共享。
用UITextBorderStyleNone: Swift设置UITextField的填充
基于@Evil Trout投票最多的答案,我在我的ViewController类中创建了一个自定义方法,如下所示:
- (void) modifyTextField:(UITextField *)textField
{
UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 20)];
textField.leftView = paddingView;
textField.leftViewMode = UITextFieldViewModeAlways;
textField.rightView = paddingView;
textField.rightViewMode = UITextFieldViewModeAlways;
[textField setBackgroundColor:[UIColor whiteColor]];
[textField setTextColor:[UIColor blackColor]];
}
现在我可以调用该方法内部(viewDidLoad方法),并发送我的任何TextFields到该方法,并为左右添加填充,并通过只写一行代码给出文本和背景颜色,如下所示:
[self modifyTextField:self.firstNameTxtFld];
这在iOS 7上非常完美! 我知道添加太多的视图可能会使这个类的加载变得更重一些。但当考虑到其他解决方法的难度时,我发现自己更偏向于这种方法,使用这种方法也更灵活。;)
感谢黑客“邪恶鳟鱼”!(鞠躬)
我认为我应该用Swift更新这个答案的代码片段:
既然Swift允许我们为现有的类写扩展,我们就这样写吧。
extension UITextField {
func addPaddingToTextField() {
let paddingView: UIView = UIView.init(frame: CGRectMake(0, 0, 8, 20))
self.leftView = paddingView;
self.leftViewMode = .Always;
self.rightView = paddingView;
self.rightViewMode = .Always;
self.backgroundColor = UIColor.whiteColor()
self.textColor = UIColor.blackColor()
}
}
用法:
self.firstNameTxtFld.addPaddingToTextField()
希望这对其他人有帮助! 干杯!