【问题标题】:- (CGRect) textRectForBounds:(CGRect)bounds not being called- (CGRect) textRectForBounds:(CGRect)bounds 没有被调用
【发布时间】:2014-04-11 22:34:48
【问题描述】:

我正在尝试在 UITextField 中移动文本,以便正确垂直对齐。我在网上搜索过,一切都指向编辑这些方法:

- (CGRect) textRectForBounds:(CGRect)bounds

- (CGRect) editingRectForBounds:(CGRect)bounds

虽然我是这样编辑它们的:

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

虽然它没有进入 nslog。

我也尝试在文本字段上调用该方法,但没有成功

这就是我初始化文本视图和设置它们的方式:

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

【问题讨论】:

  • 你需要继承 UITextField 并覆盖 - (CGRect) textRectForBounds:(CGRect)bounds 方法。
  • 我该怎么做@pawan
  • 发布代码。你现在怎么样了?

标签: ios iphone objective-c uitextfield padding


【解决方案1】:

第 1 步 - 首先创建自定义文本字段 MyTextField

@interface MyTextField : UITextField

第 2 步 - 根据您的要求覆盖 MyTextField 方法

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

第 3 步 - 在您的控制器类中导入 MyTextField 并创建 MyTextField 对象

#import "MyTextField.h"

-(void) viewWillAppear:(BOOL)animated {

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

}

现在每个文本字段都将按预期工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多