向 UITextField 添加顶部填充

Adding top padding to UITextField

我正在尝试将顶部填充添加到文本字段,但找不到任何有用的东西,所有解决方案都是关于我已经知道的左右填充。为了清楚起见,我想像下图那样。

注意:我为 "Description" 使用了标签,并将其放在文本字段中,但标签和输入重叠了。

Text Field Design

使用自定义文本字段class

class CustomTextField: UITextField {

    let padding = UIEdgeInsets(top: 15, left: 0, bottom: 0, right: 0);

    override func textRect(forBounds bounds: CGRect) -> CGRect {
        return UIEdgeInsetsInsetRect(bounds, padding)
    }

    override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
        return UIEdgeInsetsInsetRect(bounds, padding)
    }

    override func editingRect(forBounds bounds: CGRect) -> CGRect {
        return UIEdgeInsetsInsetRect(bounds, padding)
    }
}

Swift 4 版本,根据下面 Micah 的回答:

class CustomTextField: UITextField {

    let padding = UIEdgeInsets(top: 15, left: 0, bottom: 0, right: 0);

    override func textRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.inset(by: padding)
    }

    override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.inset(by: padding)
    }

    override func editingRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.inset(by: padding)
    }
}

参考已接受的答案,请注意,对于 Swift 4,您需要更改

return UIEdgeInsetsInsetRect(bounds, padding)

进入

return bounds.inset(by: padding)