macOS 13.2下UITextField点击后错位问题求助
UITextField在macOS iPad兼容模式下点击偏移的解决方法
问题说明
原本设置为居中对齐的UITextField,在macOS 13.2系统中以“My Mac(Designed for iPad)”方式构建运行时,点击文本框后文本会向左偏移;但在iPad设备上运行完全正常,Xcode 14.1和14.2版本均存在此现象。
复现代码
import UIKit class ViewController: UIViewController { let textField: UITextField = { let textField = UITextField() textField.translatesAutoresizingMaskIntoConstraints = false textField.backgroundColor = .green textField.textAlignment = .center textField.text = "Hello, World" return textField }() override func viewDidLoad() { super.viewDidLoad() view.addSubview(textField) NSLayoutConstraint.activate([ textField.widthAnchor.constraint(equalToConstant: 200), textField.heightAnchor.constraint(equalToConstant: 50), textField.centerXAnchor.constraint(equalTo: view.centerXAnchor), textField.centerYAnchor.constraint(equalTo: view.centerYAnchor) ]) } }
解决方法
这是macOS上iPad App兼容模式的UIKit已知bug,可通过以下两种方式修复:
方式一:自定义UITextField子类强制保持对齐
创建自定义子类,在文本框获取/失去焦点时强制重置居中对齐:
import UIKit class CenteredTextField: UITextField { override func becomeFirstResponder() -> Bool { let success = super.becomeFirstResponder() self.textAlignment = .center return success } override func resignFirstResponder() -> Bool { let success = super.resignFirstResponder() self.textAlignment = .center return success } }
将原代码中的UITextField替换为CenteredTextField即可生效。
方式二:监听编辑状态通知重置对齐
在ViewController中添加通知监听,响应文本框编辑状态变化:
override func viewDidLoad() { super.viewDidLoad() view.addSubview(textField) // 监听编辑开始/结束通知 NotificationCenter.default.addObserver( self, selector: #selector(resetTextAlignment), name: UITextField.textDidBeginEditingNotification, object: textField ) NotificationCenter.default.addObserver( self, selector: #selector(resetTextAlignment), name: UITextField.textDidEndEditingNotification, object: textField ) NSLayoutConstraint.activate([ textField.widthAnchor.constraint(equalToConstant: 200), textField.heightAnchor.constraint(equalToConstant: 50), textField.centerXAnchor.constraint(equalTo: view.centerXAnchor), textField.centerYAnchor.constraint(equalTo: view.centerYAnchor) ]) } @objc private func resetTextAlignment() { textField.textAlignment = .center } // 页面销毁时移除通知监听 deinit { NotificationCenter.default.removeObserver(self) }
效果验证
两种方法均能确保文本框在点击编辑和失去焦点时,始终保持文本居中对齐,解决macOS兼容模式下的偏移问题。
内容的提问来源于stack exchange,提问作者Denny
相关产品推荐
相关产品推荐

