【问题标题】:UItextfield text covers the clear button in the textfield in SwiftUItextfield 文本覆盖 Swift 中文本字段中的清除按钮
【发布时间】:2021-10-15 07:46:42
【问题描述】:

您好,我现在正在处理 UITextField,如上图所示,文本覆盖了清除按钮,我想修复它。 在这个文本字段中,我在文本的左侧和清除按钮的右侧添加了填充。

class testTextField: UITextField {

override init(frame: CGRect) {
    super.init(frame: frame)
    commonInit()
}

required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func commonInit() {
    let leftPadding = UIView(frame: CGRect(x: 0, y: 0, width: 17, height: 0))
    leftPadding.backgroundColor = .clear
    self.leftView = leftPadding
    self.leftViewMode = .always

    // tried adding padding to the rightView, but it hide the clear button
    // let rightPadding = UIView(frame: CGRect(x: 0, y: 0, width: 1, height: 0))
    // rightPadding.backgroundColor = .red
    // self.rightView = rightPadding
    // self.rightViewMode = .always
    
    
    self.backgroundColor = .white
    self.borderStyle = .none
    self.layer.cornerRadius = 12
    self.font = UIFont.systemFont(ofSize: 16)
    self.textColor = .black
    self.clearButtonMode = .whileEditing
    self.isUserInteractionEnabled = true
    
}

override func clearButtonRect(forBounds bounds: CGRect) -> CGRect {
    let originalRect = super.clearButtonRect(forBounds: bounds)
    return originalRect.offsetBy(dx: -22, dy: 0)
}

// also tried changing the width of the textRext, but after I implement the following code, the textfield becomes non-clickable...
// override func textRect(forBounds bounds: CGRect) -> CGRect {
//    self.bounds.size.width = bounds.size.width - 20.0;
//        return bounds;
//    }
// override func editingRect(forBounds bounds: CGRect) -> CGRect {
//    self.bounds.size.width = bounds.size.width - 20.0;
//        return bounds;
//    }
}

在做了一些研究(如this)后,我在代码中添加了一些 cmets,我尝试向 rightView 添加填充并更改 textRect,但它们都不起作用。

我想将清除按钮保留在现在的位置,但我想在清除按钮的左侧留出一些空间,如下图所示...

【问题讨论】:

  • @Shadowrun 很抱歉问这个问题,但你的意思是我继承了我的 testTextField 类?我认为 class testTextField: UITextField 已经是子类化,我尝试覆盖 editingRect 但不起作用..(对不起,我太初学者无法编写 Swift 并且还不习惯,所以如果我没有正确子类化,请纠正我...... )
  • 啊我没看到,问题是你试图改变你的边界,而不是计算边界值:你不想在这里使用任何赋值:self.bounds.size .width = bounds.size.width - 20.0;只需使用正确的值创建一个新的 CGRect 并返回它。也请用大写字母命名您自己的类型,如“TestTextField”,如 Int 和 String 等
  • @Shadowrun 啊,现在我明白你的意思了!非常感谢!问题解决了!!

标签: swift xcode uitextfield


【解决方案1】:

感谢@Shadowrun,我能够解决我遇到的问题。

我需要继承 UITextField 并添加editingRect。然后用我想输入的任何数字返回 CGRect。我的代码是这样的。

override func editingRect(forBounds bounds: CGRect) -> CGRect {
    return CGRect(x: 17, y: 0, width: bounds.size.width - 70, height: bounds.size.height)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-29
    • 1970-01-01
    • 1970-01-01
    • 2019-06-10
    相关资源
    最近更新 更多