ios - 具有覆盖占位符的自定义 UITextField 无法按预期工作

标签 ios swift uitextfield

我创建了一个自定义 UITextField,其中覆盖了 placeholder 属性。每当将值写入 placeholder 属性时,都会创建一个 NSAttributedString 并将其分配给 attributedPlaceholder

自定义类的代码如下-

class CustomTextField: UITextField {
    override var placeholder: String? {
        get {
            return attributedPlaceholder?.string
        }
        set {
            let attributes: [NSAttributedString.Key: Any] = [.foregroundColor: UIColor.green]
            attributedPlaceholder = NSAttributedString(string: newValue ?? "", attributes: attributes)
        }
    }
}

我在 Storyboard中创建了一个 UITextField 并将其自定义类指定为 CustomTextField。我将 Storyboard中的“Placeholder”属性设置为某个值。

当应用程序运行时,占位符显示为灰色,而不是预期的绿色。

任何人都可以指出为什么应用程序运行时不显示 attributedPlaceholder 吗?

最佳答案

你在这里

    extension CustomTextField {

    @IBInspectable var placeholderColor: UIColor? {
        get {
            return self.placeholderColor
        }
        set {
            attributedPlaceholder = NSAttributedString(string: placeholder != nil ? placeholder! : "", attributes: [.foregroundColor: newValue!])
        }
    }

}

您可以通过 Storyboard或代码访问占位符颜色 希望对您有所帮助

关于ios - 具有覆盖占位符的自定义 UITextField 无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57359922/

相关文章:

iOS App HTTP 不安全调用在本地测试中有效,但在存档后失败

ios - 如何禁用特定 View (名为 "sideV1"和 "sideV2")的 TouchsBegan 函数点击快速?

ios - UICollectionView 不保留 UITextfield 输入

flutter - 在 Flutter 中弹出时清除 TextField 中的文本

ios - 在 swift4 中移动 View 时屏幕是黑色的

javascript - 检测滑动手势 iOS - Cordova/Phonegap Javascript

ios - 使用 CABasicAnimation 为 UITextField 绘制描边动画

iphone - Box2D 无限循环 (b2World::SolveTOI)

ios - 如何使用google api获取用户位置

ios - 错误 EXC 错误指令试图从另一个类获取当前位置?