You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 00:35:11