设置 UILabel 和 UITextField 的 Padding 或 Insets (理解UIEdgeInsets)
转自http://unmi.cc/uilable-uitextfield-padding-insets 主要是理解下UIEdgeInsets在IOS UI里的意义.
靠,这货其实就是间隔,起个名字这么让人费解!!!正值表示间隔值,负值表示超出参照物的距离。
--------------------分割线,下面是转载原文---------------------------------------------------
iOS 的控件,只看到 UIButton 可以设置 Padding/Insets,即按钮上文字或图片与按钮边界的间隙,对与 CSS 来说叫做 Padding,在 iOS 中叫做 Insets,UIButton 设置 Insets 相应的属性如下:
Configuring Edge Insets
contentEdgeInsets property titleEdgeInsets property imageEdgeInsets property
//1.header file#import <UIKit/UIKit.h> @interface InsetsLabel : UILabel@property(nonatomic) UIEdgeInsets insets;-(id) initWithFrame:(CGRect)frame andInsets: (UIEdgeInsets) insets;-(id) initWithInsets: (UIEdgeInsets) insets;@end //2. implementation file#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)];}
//// Created by Unmi on 11/2/11.// Copyright (c) 2011 http://unmi.cc. All rights reserved.// #import <UIKit/UIKit.h> @interface InsetsTextField : UITextField@end @implementation InsetsTextField//控制 placeHolder 的位置,左右缩 20- (CGRect)textRectForBounds:(CGRect)bounds { return CGRectInset( bounds , 20 , 0 );} // 控制文本的位置,左右缩 20- (CGRect)editingRectForBounds:(CGRect)bounds { return CGRectInset( bounds , 20 , 0 );}@end //-----------------------------//下面是使用 InsetsTextField 的代码,可放在 viewDidLoad 等代理方法中InsetsTextField *insetTextField = [[InsetsTextField alloc] initWithFrame:CGRectMake(10, 10, 180, 25)]; //须手动设置它的 borderStyle, 不然看不到边框的insetsTextField.borderStyle = UITextBorderStyleRoundedRect;[self.view addSubview:insetsTextField];[insetsTextField release];
UILabel *paddingView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 10, 25)];paddingView.text = @"$";paddingView.textColor = [UIColor darkGrayColor];paddingView.backgroundColor = [UIColor clearColor];textfield.leftView = paddingView;textfield.leftViewMode = UITextFieldViewModeAlways;rightView 也是一样的设置方式,其中的 Mode 有四种,看到名字应该不难理解: UITextFieldViewModeNever, UITextFieldViewModeWhileEditing, UITextFieldViewModeUnlessEditing, UITextFieldViewModeAlways