设置UILabel和UITextField的Insets

Insets这个名字有点让人费解,其实它表示的是内容与控件边界的距离,相当于CSS中的padding。

目前,在iOS的控件中,只看到UIButton可以设置Insets,对应的属性是:contentEdgeInsets、titleEdgeInsets、imageEdgeInsets,它们接受的属性类型都是UIEdgeInsets,可以由函数UIEdgeInsetsMake(CGFloat top, CGFloat left, CGFloat bottom, CGFloat right)构造。在xib中也有界面来对按钮的这三个EdgeInsets属性进行设置,分别是按钮的Edge和 Inset属性。

如果想设置UILable或UITextField中的文本离边界的距离,无伦是在xib里还是直接代码的方式都无能为力,因为苹果未开放相应的属性让你去控制,所以,我们只能自定义相应的控件。

首先来看看UILabel的子类InsetsLabel的实现代码。

InsetsLabel.h

 

#import <UIKit/UIKit.h>

@interface InsetsLabel : UILabel

@property(nonatomic) UIEdgeInsets insets;

- (id)initWithFrame:(CGRect)frame andInsets:(UIEdgeInsets) insets;
- (id)initWithInsets:(UIEdgeInsets) insets;

@end

 

InsetsLabel.m

 

#import "InsetsLabel.h"

@implementation InsetsLabel

@synthesize insets = _insets;

- (id)initWithFrame:(CGRect)frame andInsets:(UIEdgeInsets)insets {
    self = [super initWithFrame:frame];
    if(self) {
        self.insets = insets;
    }
    return self;
}

- (id)initWithInsets:(UIEdgeInsets)insets {
    self = [super init];
    if(self) {
        self.insets = insets;
    }
    return self;
}

- (void)drawTextInRect:(CGRect)rect {
    return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.insets)];
}

@end

 

再来看看UITextField的子类InsetsTextField的实现代码。

 

InsetsTextField.h

 

#import <UIKit/UIKit.h>

@interface InsetsTextField : UITextField

@end

 

InsetsTextField.m

 

#import "InsetsTextField.h"

@implementation InsetsTextField

//控制placeHolder的位置
- (CGRect)textRectForBounds:(CGRect)bounds {
    return CGRectInset(bounds, 20, 0);
}

//控制文本的位置
- (CGRect)editingRectForBounds:(CGRect)bounds {
    return CGRectInset(bounds, 20, 0);
}

@end

 

上面实现InsetsTextField的方式更像是借鉴的InsetsLabel的实现,其实对于 UITextField还有更好的实现方式,而且更简单,因为这是UITextFiled本来就支持的做法。例如它可以让你做出在文本框最前方固定放一个$符号,表示这个文本框是输入金额的,这个$是不能被删除的。确实,你可以在UITextField上贴个UILabel,然后文本框的光标后移,但这个显得有点麻烦了。

 

UITextField可以直接设置leftView或rightView,然后文本输入区域就在leftView和 rightView之间了。

 

UITextField *textField = [[UITextField alloc] init];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 10, 25)];
label.text = @"$";
label.textColor = [UIColor darkGrayColor];
label.backgroundColor = [UIColor clearColor];
textField.frame = CGRectMake(0, 0, 180, 25);
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.leftView = label;
textField.leftViewMode = UITextFieldViewModeAlways;
[self.view addSubview:textField];
[label release];
[textField release];

猜你喜欢

转载自eric-gao.iteye.com/blog/1593344