UITextField添加右清除按钮后文本左移,如何保持文本居中?
解决UITextField显示清除按钮时文本偏移的问题
要让文本始终保持居中对齐,核心是让UITextField在编辑状态(显示清除按钮)和非编辑状态下的文本显示区域保持一致,避免系统自动挤压文本空间。以下是修改后的实现:
class CustomTextField: UITextField { override func awakeFromNib() { super.awakeFromNib() layer.backgroundColor = UIColor(red: 249/255, green: 250/255, blue: 250/255, alpha: 1).cgColor layer.cornerRadius = 15 textAlignment = .center // 明确设置文本居中 // 添加清除按钮 let clearButton = UIButton(type: .custom) clearButton.setImage(UIImage(systemName: "xmark.circle.fill"), for: .normal) clearButton.tintColor = .lightGray clearButton.frame = CGRect(x: 0, y: 0, width: 24, height: 24) clearButton.addTarget(self, action: #selector(clearText), for: .touchUpInside) rightView = clearButton rightViewMode = .whileEditing } override func rightViewRect(forBounds bounds: CGRect) -> CGRect { var rect = super.rightViewRect(forBounds: bounds) rect.origin.x -= 10 // 左移清除按钮10pt return rect } // 定义非编辑状态的文本显示区域 override func textRect(forBounds bounds: CGRect) -> CGRect { let buttonWidth = rightView?.bounds.width ?? 0 let inset = buttonWidth + 10 // 按钮宽度+偏移量,保证文本不被按钮遮挡 return bounds.inset(by: UIEdgeInsets(top: 0, left: inset, bottom: 0, right: inset)) } // 编辑状态下复用非编辑状态的文本区域,避免偏移 override func editingRect(forBounds bounds: CGRect) -> CGRect { return textRect(forBounds: bounds) } @objc func clearText() { text = "" } }
关键说明
- 明确设置
textAlignment = .center,确保文本居中的基础配置。 - 重写
textRect和editingRect方法,让两种状态下的文本显示区域完全一致:通过设置左右对称的内边距(等于清除按钮宽度+偏移量),既保证文本居中,又避免文本被按钮遮挡。 - 保留你原有的
rightViewRect重写逻辑,不影响按钮的位置调整。
内容的提问来源于stack exchange,提问作者Royal_Scribblz
相关产品推荐
相关产品推荐

