- (CGRect) textRectForBounds:(CGRect)bounds not being called

谁说我不能喝 提交于 2019-12-11 08:24:41

问题


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];
    }
}

回答1:


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.



来源:https://stackoverflow.com/questions/22272800/cgrect-textrectforboundscgrectbounds-not-being-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!