Swift 中默认闪烁光标

Blinking cursor as default in Swift

如何在不触摸任何地方的情况下打开视图时使光标闪烁。我目前正在使用 becomeFirstResponder() 我的文本字段成为真正的第一响应者但是当视图打开时,闪烁不会闪烁。为什么?

我的代码在这里。

import UIKit
class ViewController: UIViewController {
    let resultTextField: UITextField = {
        var myField = UITextField()
        myField.textColor = .blue
        myField.font = .systemFont(ofSize: 36)
        myField.textAlignment = .right
        myField.borderStyle = .roundedRect
        return myField
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(resultTextField)
        resultTextField.becomeFirstResponder()
        resultTextField.inputView = UIView()
    }
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        let myWidth = self.view.frame.width
        let myHeight = self.view.frame.height
        resultTextField.frame = CGRect(x: (myWidth - (myWidth / 1.15))/2,
                                       y: myHeight / 7.5,
                                       width: myWidth / 1.15,
                                       height: myHeight / 15)
    }
}

谢谢

我同意@Luca,尝试在viewDidAppear 或您的layoutSubviews 函数中调用becomeFirstResponder。 viewDidLoad()只表示你的UIViewController已经加载到内存中,但是还没有显示出来。验证这一点的简单方法是实现 UITextField 的子类并覆盖 caretRect 光标框架 returns。设置断点并测试代码...

class CustomTextField: UITextField {
   override func caretRect(for position: UITextPosition) -> CGRect {
      /// set a breakpoint and you will notice that it's not called with the viewDidLoad() of your UIViewController 
      return super.caretRect(for: position)
   }
}