ios - 无法在子类 UITextField 中设置属性占位符的文本颜色

标签 ios swift uitextfield

这是我的 UITextField 子类的简化版本:

class MyTextField: UITextField {

    override func drawPlaceholder(in rect: CGRect) {
        if let placeholder = self.placeholder {
            print(placeholder) // -> prints the value
            let attributes = [NSForegroundColorAttributeName: UIColor.red]
            self.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: attributes)
        }
    }
}

在 IB 中,文本字段分配给了我的子类,但无论我将其设置为“Plain”还是“Attributed”、字体、颜色等都没有关系。我确实给它一个初始占位符值,但是当我运行应用程序它只是空白。有什么建议吗?

最佳答案

您正在覆盖 drawPlaceholder 方法而不是调用 super。并且您的替换代码不会尝试实际绘制占位符文本。因此占位符永远不会出现。

为什么不覆盖 placeholder 属性的 setter,以便它根据需要设置 attributedPlaceholder。然后你不需要覆盖 drawPlaceholder 一切都会工作。

关于ios - 无法在子类 UITextField 中设置属性占位符的文本颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39907459/

相关文章:

ios - 旋转 ImageView 动画

ios - 核心数据反向关系ios

ios - self.collectionView 和 UICollectionViewCell.self 的区别

objective-c - 如何通过 StoryBoard 在 DatePicker 中添加一个 "Done"按钮?

ios - 如何在 NSOperation 中运行异步进程

ios - 为什么协议(protocol)在 swift 中优于类?

ios - WKWebView 正在切断我在 Xcode 9 和 Swift 4.0 中的其他 View

c++ - 在独立的 Xcode playground 中运行 c 或 c++ 代码

ios - 在 UITextfield 中创建 UIButton

ios - iOS点击UITextField时如何显示弹出菜单列表? (Kx菜单)