由于苹果没有提供创建选择器的类,所以自己做了一个选择器,主要是通过UIButton来实现,希望可以帮助大家,如果有不好的地方希望能给我提出来。下面是我选择器实现的方法
<span style="font-size:14px;">#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//设置背景图
UIImage *backgroundImage = [UIImage imageNamed: [[NSBundle mainBundle] pathForResource:@"Login_Background_Image" ofType:@"jpg"]];
UIImageView *backgroundImageView = [[UIImageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
backgroundImageView.image = backgroundImage;
[self.view addSubview:backgroundImageView];
//初始化UITextField
NSArray *placeholderArray = @[@"请输入账号", @"请输入密码"];
CGFloat textFieldX = 10;
CGFloat textFieldY = 100;
CGFloat textFieldW = CGRectGetWidth([UIScreen mainScreen].bounds) - textFieldX * 2;
CGFloat textFieldH = 44;
for (int i = 0; i < placeholderArray.count; i ++) {
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(textFieldX, textFieldY + (textFieldH + 10) * i, textFieldW, textFieldH)];
textField.placeholder = placeholderArray[i];
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.tag = 10 + i;
[self.view addSubview:textField];
}
//初始化选择器按钮
UIButton *checkbox=[[UIButton alloc]initWithFrame:CGRectZero];
[self.view addSubview:checkbox];
UITextField *textField = (UITextField *)[self.view viewWithTag:11];
checkbox.frame = CGRectMake(30, CGRectGetMaxY(textField.frame) + 20, 20, 20);
[checkbox setImage:[UIImage imageNamed:@"userChoose.png"]forState:UIControlStateNormal];
[checkbox setImage:[UIImage imageNamed:@"success.png"]forState:UIControlStateSelected];
[checkbox addTarget:self action:@selector(checkboxClick:)forControlEvents:UIControlEventTouchUpInside];
[checkbox setSelected:NO];//设置按钮得状态是否为选中(可在此根据具体情况来设置按钮得初始状态)
CGFloat labelX = CGRectGetMaxX(checkbox.frame) + 5;
CGFloat labelY = CGRectGetMaxY(textField.frame) + 20;
CGFloat labelW = 100;
CGFloat labelH = 20;
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(labelX, labelY, labelW, labelH)];
label.text = @"记住密码";
label.textColor = [UIColor whiteColor]
;
label.font = [UIFont boldSystemFontOfSize:15];
[self.view addSubview:label];
}</span>
实现checkbox方法
//实现checkboxClick方法
-(void)checkboxClick:(UIButton *)sender{
sender.selected = !sender.selected;//每次点击都改变按钮的状态
if (sender.selected){
}else{
//在此实现打勾时的方法
}
//在此实现不打勾时的方法
}
没有选择记住密码之前的效果
选择记住密码之后