编辑开始时更改 UITextField 背景
我想在 UITextField 成为第一个响应者时更改其背景图像,以向用户显示它具有焦点,类似于 CSS 中的 :active 或 :focus 伪类。
我猜我可能需要以编程方式执行此操作;所以非常感谢任何帮助。
-贾尔斯
I'd like to change the background image of a UITextField when it becomes the firstResponder to show the user that it has focus, similar to the :active or :focus pseudo-classes in CSS.
I'm guessing that I may need to do this programmatically; so any help is greatly appreciated.
-Giles
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
恕我直言,最简洁的方法是子类化
UITextField
并覆盖becomeFirstResponder
和resignFirstResponder
来更改文本字段的背景图像。这样,您就可以在任何地方使用新的子类,而无需重新实现委托方法来更改背景。The cleanest way IMHO is to subclass
UITextField
and overridebecomeFirstResponder
andresignFirstResponder
to change the background image of the text field. That way, you can use your new subclass anywhere without having to reimplement the delegate methods to change the background.您也可以使用 UITextFieldDelegate 方法(恕我直言,比键值观察者更容易维护):
这仅在 UITextField.borderStyle 属性是除 UITextBorderStyleRoundedRect 之外的任何类型时才有效(在这种情况下,不考虑背景属性) 。这意味着您可以将上面的代码与 UITextBorderStyleBezel、UITextBorderStyleLine 和 UITextBorderStyleNone 一起使用,如 borderStyle 文档中所述:
这是 UITextField 的背景属性的文档:
You might as well use the UITextFieldDelegate methods (IMHO, easier to maintain than key-value observers):
This only works when the UITextField.borderStyle property is of any type but UITextBorderStyleRoundedRect (in that case, the background property is not taken into account). This means you might use the code above with UITextBorderStyleBezel, UITextBorderStyleLine and UITextBorderStyleNone, as explained in the borderStyle documentation:
This is the documentation for the background property of UITextField:
SWIFT 4
SWIFT 4
您可以尝试观察 isFirstResponder 的变化。并更改通知方法中的背景。像这样:
然后在观察者中:
You can probably try observing for changes to isFirstResponder. and changing the background in the notification method. Something like:
Then in the observer: