我想为我的UITextFields使用一个自定义背景。这很好,除了我必须使用UITextBorderStyleNone来使它看起来很漂亮。这将迫使文本保持在左边,没有任何填充。

我可以手动设置填充,使它看起来类似于UITextBorderStyleRoundedRect除了使用我的自定义背景图像?


当前回答

我是基于Nate的解决方案,但后来我发现,这导致问题,当你使用leftView/rightView属性,所以它更好地调优超级的实现,因为它将左/右视图的考虑。

- (CGRect)textRectForBounds:(CGRect)bounds {
    CGRect ret = [super textRectForBounds:bounds];
    ret.origin.x = ret.origin.x + 5;
    ret.size.width = ret.size.width - 10;
    return ret;
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
    return [self textRectForBounds:bounds];
}

其他回答

我创建了这个类别实现,并将其添加到.m文件的顶部。

@implementation UITextField (custom)
    - (CGRect)textRectForBounds:(CGRect)bounds {
        return CGRectMake(bounds.origin.x + 10, bounds.origin.y + 8,
                          bounds.size.width - 20, bounds.size.height - 16);
    }
    - (CGRect)editingRectForBounds:(CGRect)bounds {
        return [self textRectForBounds:bounds];
    }
@end

根据彼得·布拉斯亚克提供的链接。这似乎比创建一个全新的子类更简单,也比添加额外的UIView更简单。不过,似乎缺少了一些东西,无法控制文本字段内的填充。

Swift 4解决方案:

class CustomTextField: UITextField {
    struct Constants {
        static let sidePadding: CGFloat = 10
        static let topPadding: CGFloat = 8
    }

    override func textRect(forBounds bounds: CGRect) -> CGRect {
        return CGRect(
            x: bounds.origin.x + Constants.sidePadding,
            y: bounds.origin.y + Constants.topPadding,
            width: bounds.size.width - Constants.sidePadding * 2,
            height: bounds.size.height - Constants.topPadding * 2
        )
    }

    override func editingRect(forBounds bounds: CGRect) -> CGRect {
        return self.textRect(forBounds: bounds)
    }
}
textField.layer.borderWidth = 3;

将添加边框,这对我来说是填充。

以下是如何在SWIFT中实现这一点

@IBOutlet weak var yourTextField: UITextField!

override func viewDidLoad() {
super.viewDidLoad()
let paddingView = UIView(frame: CGRectMake(0, 0, 10, self.yourTextField.frame.height))
yourTextField.leftView = paddingView
yourTextField.leftViewMode = UITextFieldViewMode.Always
}
}

资源

斯威夫特版本:

extension UITextField {
    @IBInspectable var padding_left: CGFloat {
        get {
            LF.log("WARNING no getter for UITextField.padding_left")
            return 0
        }
        set (f) {
            layer.sublayerTransform = CATransform3DMakeTranslation(f, 0, 0)
        }
    }
}

这样你就可以在IB中赋值

另一个需要考虑的问题是,如果你在添加填充的地方有多个UITextField,就要为每个文本字段创建一个单独的UIView——因为它们不能共享。