uitextfield 設置左圖標以及圖標文字間距,輸入框背景圖切換

參考網上資料,直接使用網上的代碼,沒有實現,重新修改
YLSTextField文件

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

#import "YLSTextField.h"
@implementation YLSTextField
//改變文字位置
-(CGRect) textRectForBounds:(CGRect)bounds{
    CGRect iconRect=[super textRectForBounds:bounds];
    iconRect.origin.x+=10;
    return iconRect;
}
//改變編輯時文字位置
-(CGRect) editingRectForBounds:(CGRect)bounds{
    CGRect iconRect=[super editingRectForBounds:bounds];
    iconRect.origin.x+=10;
    return iconRect;
}
@end

頁面中代碼

self.loginuser.delegate=self;
    self.loginpass.delegate=self;
    //設置輸入框左邊圖標
    UIImageView *image1=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"user.png"]];
    image1.frame=CGRectMake(0, 0, 27, 27);
    self.loginuser.leftView=image1;
    self.loginuser.leftViewMode=UITextFieldViewModeAlways;
    UIImageView *image2=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"mima.png"]];
    image2.frame=CGRectMake(0, 0, 27, 27);
    self.loginpass.leftView=image2;
    self.loginpass.leftViewMode=UITextFieldViewModeAlways;

輸入框點擊時背景圖改變,不知道爲啥在storyboard中設置的沒有起作用。

//改變輸入框背景圖片
-(void)textFieldDidBeginEditing:(YLSTextField *)textField{
    if (textField.tag==3) {
        [self.loginuser setBackground:[UIImage imageNamed:@"inputlan.png"]];
    }else if(textField.tag==4){
        [self.loginpass setBackground:[UIImage imageNamed:@"inputlan.png"]];
    }
}

-(void)textFieldDidEndEditing:(YLSTextField *)textField{
    if (textField.tag==3) {
        [self.loginuser setBackground:[UIImage imageNamed:@"inputhui.png"]];
    }else if(textField.tag==4){
        [self.loginpass setBackground:[UIImage imageNamed:@"inputhui.png"]];
    }
}
發佈了119 篇原創文章 · 獲贊 6 · 訪問量 51萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章