效果圖
實(shí)現(xiàn)方法
//創(chuàng)建左側(cè)視圖
UIImage *im = [UIImage imageNamed:@"icon"];
UIImageView *iv = [[UIImageView alloc] initWithImage:im];
UIView *lv = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 200)];//寬度根據(jù)需求進(jìn)行設(shè)置拭卿,高度必須大于 textField 的高度
lv.backgroundColor = [UIColor blueColor];
iv.center = lv.center;
[lv addSubview:iv];
//設(shè)置 textField 的左側(cè)視圖
//設(shè)置左側(cè)視圖的顯示模式
tf.leftViewMode = UITextFieldViewModeAlways;
tf.leftView = lv;
左側(cè)視圖屬性
@property(nonatomic) UITextFieldViewMode leftViewMode;// sets when the left view shows up. default is UITextFieldViewModeNever
typedef NS_ENUM(NSInteger, UITextFieldViewMode) {
UITextFieldViewModeNever,//不顯示左側(cè)視圖
UITextFieldViewModeWhileEditing,//只在編輯時(shí)顯示左側(cè)視圖
UITextFieldViewModeUnlessEditing,//編輯時(shí)隱藏左側(cè)視圖
UITextFieldViewModeAlways//總是顯示左側(cè)視圖
};
代碼示例
UITextField *tf = [[UITextField alloc] init];
tf.borderStyle = UITextBorderStyleRoundedRect;
tf.placeholder = @"請(qǐng)輸入手機(jī)號(hào)";
[self.view addSubview:tf];
tf.center = self.view.center;
UIImage *im = [UIImage imageNamed:@"icon"];
UIImageView *iv = [[UIImageView alloc] initWithImage:im];
UIView *lv = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 200)];
lv.backgroundColor = [UIColor blueColor];
iv.center = lv.center;
[lv addSubview:iv];
tf.leftViewMode = UITextFieldViewModeAlways;
tf.leftView = lv;
[tf sizeToFit];