效果图
实现方法
//创建左侧视图
UIImage *im = [UIImage imageNamed:@"icon"];
UIImageView *iv = [[UIImageView alloc] initWithImage:im];
UIView *lv = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 200)];//宽度根据需求进行设置,高度必须大于 textField 的高度
lv.backgroundColor = [UIColor blueColor];
iv.center = lv.center;
[lv addSubview:iv];
//设置 textField 的左侧视图
//设置左侧视图的显示模式
tf.leftViewMode = UITextFieldViewModeAlways;
tf.leftView = lv;
左侧视图属性
@property(nonatomic) UITextFieldViewMode leftViewMode;// sets when the left view shows up. default is UITextFieldViewModeNever
typedef NS_ENUM(NSInteger, UITextFieldViewMode) {
UITextFieldViewModeNever,//不显示左侧视图
UITextFieldViewModeWhileEditing,//只在编辑时显示左侧视图
UITextFieldViewModeUnlessEditing,//编辑时隐藏左侧视图
UITextFieldViewModeAlways//总是显示左侧视图
};
代码示例
UITextField *tf = [[UITextField alloc] init];
tf.borderStyle = UITextBorderStyleRoundedRect;
tf.placeholder = @"请输入手机号";
[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];