Roei Nadam
Roei Nadam

Reputation: 1780

How to vertically center the cursor in a UITextView

I try to vertically center my text cursor in a UITextView.

// creating the inputText
[inputTextView removeFromSuperview];
inputTextView = [[UITextView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(searchIconsButton.frame) + 3 , 0, buttomView.frame.size.width * 0.78 , buttomView.frame.size.height *0.80)];
inputTextView.layer.borderColor = [UIColor lightGrayColor].CGColor;
inputTextView.layer.borderWidth = 0.6;
inputTextView.center = CGPointMake(inputTextView.center.x, buttomView.frame.size.height / 2);
inputTextView.autocorrectionType = UITextAutocorrectionTypeNo;
[inputTextView.layer setCornerRadius:6];
[inputTextView setTintColor:[UIColor blackColor]]; // set the cursor color to black
inputTextView.textAlignment = UIControlContentVerticalAlignmentCenter;

I try in last line to do UIControlContentVerticalAlignmentCenter but it still do not work .

You can see that the cursor hides into the Textview.

There is a way to solve it?

Upvotes: 5

Views: 2200

Answers (3)

Arik Segal
Arik Segal

Reputation: 3031

I know that this has already been answered but the answers didn't work for me. I have managed to achieve the desired difference in caret positioning by overriding this method:

-(CGRect) caretRectForPosition:(UITextPosition *)position
{
    CGRect nativeRect = [super caretRectForPosition:position];
    NSLog(@"nativeRect x:%f y:%f w:%f h:%f ", nativeRect.origin.x, nativeRect.origin.y, nativeRect.size.width, nativeRect.size.height);

    // Here you can do something with the desired positioning and size (for examaple, I incremented y):
    return CGRectMake(nativeRect.origin.x, nativeRect.origin.y + 2, nativeRect.size.width, nativeRect.size.height);
}

Upvotes: 0

GyroCocoa
GyroCocoa

Reputation: 1612

The solution above is perfect but for those who are using swift 3 I have translated to the following ad its working perfectly.

  override func editingRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.insetBy(dx: 0, dy: 2);
    }

Overriding the UITextField ofcouse

Upvotes: 0

Eric Amorde
Eric Amorde

Reputation: 1068

Use the textContainerInset property of UITextView, available iOS 7.0 and later.

inputTextView.textContainerInset = UIEdgeInsetsMake(-2,0,0,0); // Move cursor up 2

Play around with the values until it fits your needs.

Upvotes: 6

Related Questions