歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 設置UILabel和UITextField的Insets

設置UILabel和UITextField的Insets

日期:2017/3/1 10:11:05   编辑:Linux編程

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. @interface InsetsLabel : UILabel
  3. @property(nonatomic) UIEdgeInsets insets;
  4. - (id)initWithFrame:(CGRect)frame andInsets:(UIEdgeInsets) insets;
  5. - (id)initWithInsets:(UIEdgeInsets) insets;
  6. @end

InsetsLabel.m

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

再來看看UITextField的子類InsetsTextField的實現代碼。

InsetsTextField.h

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

InsetsTextField.m

  1. #import "InsetsTextField.h"
  2. @implementation InsetsTextField
  3. //控制placeHolder的位置
  4. - (CGRect)textRectForBounds:(CGRect)bounds {
  5. return CGRectInset(bounds, 20, 0);
  6. }
  7. //控制文本的位置
  8. - (CGRect)editingRectForBounds:(CGRect)bounds {
  9. return CGRectInset(bounds, 20, 0);
  10. }
  11. @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(0, 0, 10, 25)];
  3. label.text = @"$";
  4. label.textColor = [UIColor darkGrayColor];
  5. label.backgroundColor = [UIColor clearColor];
  6. textField.frame = CGRectMake(0, 0, 180, 25);
  7. textField.borderStyle = UITextBorderStyleRoundedRect;
  8. textField.leftView = label;
  9. textField.leftViewMode = UITextFieldViewModeAlways;
  10. [self.view addSubview:textField];
  11. [label release];
  12. [textField release];
Copyright © Linux教程網 All Rights Reserved