Swift开发中UITextField输入文本遮挡clearButton清除按钮如何修复
解决方法很简单,你之前修改textRect和editingRect的写法错误,导致控件响应异常,不要在这两个方法内修改self.bounds,直接返回裁剪后的文本显示区域即可。
修正后完整代码
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 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) } override func textRect(forBounds bounds: CGRect) -> CGRect { // 右侧缩进=系统清除按钮宽度(约19pt)+ 你需要的按钮左侧留白,这里8pt可自行调整 let rightInset: CGFloat = 27 return super.textRect(forBounds: bounds).inset(by: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: rightInset)) } override func editingRect(forBounds bounds: CGRect) -> CGRect { // 编辑状态和普通状态保持统一缩进 let rightInset: CGFloat = 27 return super.editingRect(forBounds: bounds).inset(by: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: rightInset)) } }
说明
- 直接调用父类方法获取原始文本区域再做裁剪,不会修改控件本身的布局,完全不影响点击交互
- 右侧缩进数值可按需调整,不需要额外设置
rightView,避免和系统清除按钮冲突 - 原有清除按钮的位置逻辑完全保留,符合需求
内容的提问来源于stack exchange,提问作者Yuuu
相关产品推荐
相关产品推荐

