键入时,文本字段会切断第一个表情符号

时间:2018-12-14 18:15:54

标签: ios swift autolayout uitextfield

我有一个文本字段,其大小与它拥有的文本大小相同。当您不输入文字时,它看起来不错,但是当您开始输入文字时,它将表情符号向左移动并导致第一个表情符号被剪切掉(与文本配合使用)。

我没有使用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()
    }
}

表情符号适合不输入时使用:

Emojis fit fine when not typing

键入时,第一个表情符号被截断: First emoji is cut off when typing

1 个答案:

答案 0 :(得分:0)

您是否对文本字段设置了任何约束? 如果不尝试将其添加到堆栈视图中,我相信它应该可以工作。