Mehmet S.
Mehmet S.

Reputation: 47

Blinking cursor as default in Swift

How can I make cursor blink when the view is opened without touching anywhere. I am currently using becomeFirstResponder() My text field becomes really first responder but when the view is opened, blink does not blink. Why?

My code is here.

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)
    }
}

Thanks

Upvotes: 0

Views: 461

Answers (1)

Daniel Marx
Daniel Marx

Reputation: 764

I agree with @Luca, try calling becomeFirstResponder in viewDidAppear or in your layoutSubviews function. viewDidLoad()only means that your UIViewController has been loaded to memory but is not displayed yet. Easy way to verify this is implementing a subclass from UITextField and override the caretRect which returns the cursor's frame. Set a breakpoint and test the code ...

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)
   }
}

Upvotes: 0

Related Questions