【问题标题】:Swift - Disable text shifting when clear button appearsSwift - 出现清除按钮时禁用文本移动
【发布时间】:2016-09-10 22:49:40
【问题描述】:

我的项目中有一个 UITextField,在编辑期间启用了清除按钮。

框内任何居中的文本都会向左移动,以便为焦点上的清除按钮腾出空间。我是否可以禁用这种转变。我觉得这很让人分心。

请看下面的截图:

【问题讨论】:

    标签: ios swift swift2 uitextfield


    【解决方案1】:

    我可以禁用这个转换

    稍加小心,是的,您当然可以做到。文本的绘制实际上取决于你,如果你继承 UITextField: 你可以覆盖 drawText(in:) 和/或 textRect(forBounds:) 并负责文本的去向。

    【讨论】:

    • 我之前没有覆盖 UITextField 的需求,所以这是推测,但是你不能也覆盖文本字段的textRectForBounds 方法吗?
    • @DuncanC 呃,我就是这么说的。只有我在 Swift 3 中说过。:) Xcode 8 已经通用,是时候迈向未来了。
    • 关闭!但你肯定给我指出了正确的方向。我已经有了文本字段的子类,所以我研究了一些其他可用的功能。我需要editingRectForBounds(bounds:)。在这里找到我的答案:stackoverflow.com/questions/25367502/…
    【解决方案2】:

    为了解决这个问题,我对UITextField 进行了子类化,并在子类中添加了以下内容:

    class CustomTextField: UITextField {
        override func editingRectForBounds(bounds: CGRect) -> CGRect {
            let padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
            return UIEdgeInsetsInsetRect(bounds, padding)
        }
    }
    

    Swift 4.2 和 Xcode 10

    class CustomTextField: UITextField {
        override func editingRect(forBounds bounds: CGRect) -> CGRect {
            let padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
            return bounds.inset(by: padding)
        }
    }
    

    在这里找到答案:Create space at the beginning of a UITextField

    【讨论】:

    • 这很好用,只是编辑了答案以提供 Swift 4.2 更新的解决方案
    猜你喜欢
    • 1970-01-01
    • 2022-11-09
    • 2018-03-20
    • 2019-11-16
    • 2019-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-09
    相关资源
    最近更新 更多