设置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

  1. #import <UIKit/UIKit.h>   
  2.   
  3. @interface InsetsLabel : UILabel   
  4.   
  5. @property(nonatomic) UIEdgeInsets insets;   
  6.   
  7. - (id)initWithFrame:(CGRect)frame andInsets:(UIEdgeInsets) insets;   
  8. - (id)initWithInsets:(UIEdgeInsets) insets;   
  9.   
  10. @end  

InsetsLabel.m

  1. #import "InsetsLabel.h"  
  2.   
  3. @implementation InsetsLabel   
  4.   
  5. @synthesize insets = _insets;   
  6.   
  7. - (id)initWithFrame:(CGRect)frame andInsets:(UIEdgeInsets)insets {   
  8.     self = [super initWithFrame:frame];   
  9.     if(self) {   
  10.         self.insets = insets;   
  11.     }   
  12.     return self;   
  13. }   
  14.   
  15. - (id)initWithInsets:(UIEdgeInsets)insets {   
  16.     self = [super init];   
  17.     if(self) {   
  18.         self.insets = insets;   
  19.     }   
  20.     return self;   
  21. }   
  22.   
  23. - (void)drawTextInRect:(CGRect)rect {   
  24.     return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.insets)];   
  25. }   
  26.   
  27. @end  

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

InsetsTextField.h

  1. #import <UIKit/UIKit.h>   
  2.   
  3. @interface InsetsTextField : UITextField   
  4.   
  5. @end  

InsetsTextField.m

  1. #import "InsetsTextField.h"  
  2.   
  3. @implementation InsetsTextField   
  4.   
  5. //控制placeHolder的位置   
  6. - (CGRect)textRectForBounds:(CGRect)bounds {   
  7.     return CGRectInset(bounds, 200);   
  8. }   
  9.   
  10. //控制文本的位置   
  11. - (CGRect)editingRectForBounds:(CGRect)bounds {   
  12.     return CGRectInset(bounds, 200);   
  13. }   
  14.   
  15. @end  

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

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

  1. UITextField *textField = [[UITextField alloc] init];   
  2. UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(001025)];   
  3. label.text = @"$";   
  4. label.textColor = [UIColor darkGrayColor];   
  5. label.backgroundColor = [UIColor clearColor];   
  6. textField.frame = CGRectMake(0018025);   
  7. textField.borderStyle = UITextBorderStyleRoundedRect;   
  8. textField.leftView = label;   
  9. textField.leftViewMode = UITextFieldViewModeAlways;   
  10. [self.view addSubview:textField];   
  11. [label release];   
  12. [textField release];  

相关内容