Vatsal Shukla
Vatsal Shukla

Reputation: 1272

Weird behaviour of caret/cursor in UITextField

(Xcode10.1 ,Swift, iOS 11&12)
Question: How to increase height of caret/cursor in UITextField

What I've tried so far:
I've done this, and it works:

class BPTextField: UITextField {
    override func caretRect(for position: UITextPosition) -> CGRect {
        var rect = super.caretRect(for: position)
        let h = self.frame.height - 5
        let y_ = (self.frame.height - h)/2
        rect.origin.y = y_
        rect.size.height = h;
        return rect;
    }
}

But when I change the keyboard language (from English-India to Japanese-Kana) and type a single character, the caret/cursor moves to up side in the text field.

I've gone through these links:
How to make the height of the cursor same with the height of text in UITextField?
UITextView lineSpacing causes different cursor height inbetween paragraph lines

EDIT I'm using YYText library. I'm inserting this BPTextField into YYLabel as a NSAttributedStringAttachment:

let main = NSMutableAttributedString(string: text_)
main.yy_color = .darkGray
main.yy_font = questionFont
main.yy_lineSpacing = 5.0
main.yy_lineBreakMode = .byWordWrapping

//Attachment

let attachment = NSMutableAttributedString.yy_attachmentString(withContent: self.tf, contentMode: UIView.ContentMode.center, attachmentSize: self.tf.frame.size, alignTo: questionFont, alignment: YYTextVerticalAlignment.bottom)
attachment.yy_baselineOffset = -5.0
root.append(attachment)

//BPTextField

self.tf = BPTextField(frame: CGRect(origin: CGPoint.init(x: 0, y: 13), size: CGSize(width: tfWidth.width + 7.5, height: tfWidth.height + 13.0)))
self.tf.borderStyle = UITextField.BorderStyle.none
self.tf.tag = 0
self.tf.font = questionFont
self.tf.autocorrectionType = UITextAutocorrectionType.no
self.tf.textColor = .darkGray
self.tf.setRoundedCorners(corners: UIRectCorner.allCorners, withRadius: 4.0)
//self.tf.setLeftPaddingPoints(5.0)
//self.tf.setRightPaddingPoints(0.0)
self.tf.backgroundColor = #colorLiteral(red: 0.9058823529, green: 0.9529411765, blue: 1, alpha: 1)
self.tf.tintColor = #colorLiteral(red: 0.2196078431, green: 0.6156862745, blue: 1, alpha: 1)
self.tf.returnKeyType = .done
self.tf.delegate = self

Upvotes: 2

Views: 861

Answers (1)

Kamran
Kamran

Reputation: 15258

You can calculate origin y as below,

override func caretRect(for position: UITextPosition) -> CGRect {
    var rect = super.caretRect(for: position)
    let size = CGSize(width: rect.size.width, height: self.frame.height - 5)
    // Calculating center y
    let y = rect.origin.y - (size.height - rect.size.height)/2
    rect = CGRect(origin: CGPoint(x: rect.origin.x, y: y), size: size)
    return rect
}

Upvotes: 1

Related Questions