【发布时间】:2018-12-14 18:15:54
【问题描述】:
我有一个文本字段,其大小与它所拥有的文本量相同。不打字时它看起来不错,但当你开始打字时,它会将表情符号向左移动并导致第一个表情符号被切断(它适用于文本)。
我没有做任何手动调整大小,只是使用 sizeToFit()。
代码:
override func viewDidLoad() {
super.viewDidLoad()
let emojiTextField = UITextField.makeEmojiTextField()
emojiTextField.delegate = self
view.addSubview(emojiTextField)
emojiTextField.anchorCenterSuperview()
}
class EmojiTextField: UITextField {
override var textInputMode: UITextInputMode? {
for mode in UITextInputMode.activeInputModes {
if mode.primaryLanguage == "emoji" {
return mode
}
}
return nil
}
}
extension UITextField {
static func makeEmojiTextField() -> EmojiTextField {
let tf = EmojiTextField()
tf.placeholder = ""
tf.font = UIFont.systemFont(ofSize: 64)
tf.borderStyle = UITextField.BorderStyle.none
tf.autocorrectionType = UITextAutocorrectionType.no
tf.returnKeyType = UIReturnKeyType.done
tf.contentVerticalAlignment = UIControl.ContentVerticalAlignment.center
tf.backgroundColor = .green
return tf
}
}
extension UIView {
public func anchorCenterXToSuperview(constant: CGFloat = 0) {
translatesAutoresizingMaskIntoConstraints = false
if let anchor = superview?.centerXAnchor {
centerXAnchor.constraint(equalTo: anchor, constant: constant).isActive = true
}
}
public func anchorCenterYToSuperview(constant: CGFloat = 0) {
translatesAutoresizingMaskIntoConstraints = false
if let anchor = superview?.centerYAnchor {
centerYAnchor.constraint(equalTo: anchor, constant: constant).isActive = true
}
}
public func anchorCenterSuperview() {
anchorCenterXToSuperview()
anchorCenterYToSuperview()
}
}
不打字时表情符号很合适:
【问题讨论】:
标签: ios swift autolayout uitextfield