سؤال

I am trying to move text inside a UITextField so that it is vertically aligned correctly. I have searched online and everything points to editing these methods:

- (CGRect) textRectForBounds:(CGRect)bounds

and

- (CGRect) editingRectForBounds:(CGRect)bounds

Though I have edited them like this:

- (CGRect) textRectForBounds:(CGRect)bounds {
    NSLog(@"hi");
    return CGRectInset(bounds, 10, 10);
}

Though it doesn't get to the nslog.

I have also tried calling the method on the textfield but to no success

This is how I am initialising the text views and setting them up:

-(void) viewWillAppear:(BOOL)animated {
    textfield1 = [[UITextField alloc] init];
    textfield2 = [[UITextField alloc] init];
    textfield3 = [[UITextField alloc] init];
    textfield4 = [[UITextField alloc] init];
    for (UITextField *text in [NSArray arrayWithObjects:textfield1, textfield2, textfield3, textfield4, nil]) {
        text.delegate = self;
        text.placeholder = [placeholders objectAtIndex:i];
        text.frame = CGRectMake(10, offsetTop, container.frame.size.width - 20, 40);
        [text textRectForBounds:text.bounds];
        [text editingRectForBounds:text.bounds];
        text.borderStyle = UITextBorderStyleRoundedRect;
        offsetTop += 50;
        i++;
        [container addSubview:text];
    }
}
هل كانت مفيدة؟

المحلول

step 1 - make a custom text field MyTextField first

@interface MyTextField : UITextField

step 2 - override MyTextField methods as per your requirement

///place holder position

- (CGRect)placeholderRectForBounds:(CGRect)bounds
 {
   return CGRectInset(bounds, 8, 8);
 }
 // text position
 - (CGRect)textRectForBounds:(CGRect)bounds {

  return CGRectInset(bounds, 8,4);
 }

 // text position while editing
 - (CGRect)editingRectForBounds:(CGRect)bounds {

     return CGRectInset(bounds, 8, 4);
 }

step 3- import MyTextField in your controller class & make object of MyTextField

#import "MyTextField.h"

-(void) viewWillAppear:(BOOL)animated {

    MyTextField* textfield1 = [[MyTextField alloc] init];
    // and so on

}

now every text field will work as expected.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top