UITextField自定义背景视图和移动文本

diz*_*izy 5 iphone uitextfield

我正在尝试使用自定义文本字段背景.问题是文本在左侧看起来太近了.

我没有看到任何方法在没有子类化UITextField的情况下移动文本.所以我试图扩展和覆盖

- (void)drawTextInRect:(CGRect)rect{
    NSLog(@"draw rect");
    CGRect newRect = CGRectMake(rect.origin.x+20,rect.origin.y,rect.size.width-20,rect.size.height);    
    [super drawTextInRect:newRect]; 
}
Run Code Online (Sandbox Code Playgroud)

但由于某种原因,日志永远不会打印.我知道子类正在使用,因为我在init中也有一个日志,打印很好.

什么去了

编辑.

我也试试

- (CGRect)textRectForBounds:(CGRect)bounds{
    NSLog(@"bounds");
    CGRect b = [super textRectForBounds:bounds];
    b.origin.x += 20;
    return b;
}
Run Code Online (Sandbox Code Playgroud)

这实际上是追踪,但它似乎并没有改变

Tho*_*ler 14

我想你可以使用这个leftView属性.

您可以添加一个leftViewrightViewUITextfield.这些视图可用于显示图标,但如果它是一个空视图,它只会占用空间,这就是你想要的.

CGFloat leftInset = 5.0f;
UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, leftInset, self.bounds.size.height)];
self.leftView = leftView;
self.leftViewMode = UITextFieldViewModeAlways;
[leftView release];
Run Code Online (Sandbox Code Playgroud)


小智 7

另一个灵魂:

在appDelegate.m文件中,在顶部写下面的代码

@interface UITextField (myCustomTextField)

@end

@implementation UITextField (myCustomTextField)

- (CGRect)textRectForBounds:(CGRect)bounds {

    return CGRectInset(bounds, 10, 0);
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
    return CGRectInset(bounds, 10, 0);
}

@end
Run Code Online (Sandbox Code Playgroud)


Sea*_*ean 5

仅供参考,但我遇到了同样的问题并最终意识到还有一个editingRectForBounds:方法.当您最初在字段中输入内容时,控件会使用该控件.如果它有一个值并且不再处于编辑模式,则它使用textRectForBounds:来决定在何处绘制文本.


gef*_*gef 5

我没有尝试过托马斯的方法,只是为了澄清肖恩的答案,这对我有用:

MyInsetUITextField.m

#import "MyInsetUITextField.h"
@implementation MyInsetUITextField

- (CGRect)textRectForBounds:(CGRect)bounds {

    return CGRectInset(bounds, 10, 0);
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
    return CGRectInset(bounds, 10, 0);
}

@end
Run Code Online (Sandbox Code Playgroud)

MyInsetUITextField.h

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface MyInsetUITextField : UITextField {

}

@end
Run Code Online (Sandbox Code Playgroud)

谢谢.