Swift - UITextField填充隐藏了清除按钮

时间:2018-04-02 17:14:06

标签: swift uitextfield

我创建了一个特殊的textField,右侧有一个填充(我使用的是RTL语言)。它工作得很好,除了它隐藏了清除按钮的事实。我有什么想法可以在填充视图顶部显示清除按钮吗?

class PaddedTextField: UITextField {

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

    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)
    }
}

2 个答案:

答案 0 :(得分:0)

您无法直接访问清除按钮,但可以设置其框架和原点:

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

答案 1 :(得分:0)

只需将super.个函数添加到覆盖的函数中

private let padding = UIEdgeInsets(top: 0.5, left: 8, bottom: 0.5, right: 8)

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

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

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