读书人

设立UILabel和UITextField的Insets

发布时间: 2012-09-27 11:11:17 作者: rapoo

设置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的实现代码。

?

#import <UIKit/UIKit.h>@interface InsetsLabel : UILabel@property(nonatomic) UIEdgeInsets insets;- (id)initWithFrame:(CGRect)frame andInsets:(UIEdgeInsets) insets;- (id)initWithInsets:(UIEdgeInsets) insets;@end

#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

#import <UIKit/UIKit.h>@interface InsetsTextField : UITextField@end

#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

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

读书人网 >移动开发

热点推荐