仿支付寶支付密碼輸入框

仿支付寶支付密碼輸入框

前段時間看到小夥伴們在做一個密碼輸入框,剛好拿來複習下Quartz 2D,不廢話,直接上圖:
仿支付寶支付密碼輸入框

主要思路如下:
- UITextField上面覆蓋一個UIView
- 設置UIView的userInteractionEnabled爲NO,讓UITextField響應點擊事件
- 監控UITextField中輸入的文字內容
- 在UIView上用Quartz 2D來繪製圖形


控制器中主要代碼

//初始化界面
UITextField * pwdTextField = [[UITextField alloc] initWithFrame:CGRectMake(10, 100, self.view.frame.size.width - 20, 50)];
    pwdTextField.delegate = self;
    self.pwdTextField = pwdTextField;
    pwdTextField.backgroundColor = [UIColor yellowColor];
    pwdTextField.tintColor = pwdTextField.backgroundColor;
    [pwdTextField setTextColor:pwdTextField.backgroundColor];
    pwdTextField.alpha = 0.1;
    pwdTextField.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview:pwdTextField];

    PwdView * pwdView = [[PwdView alloc] initWithFrame:pwdTextField.frame];
    pwdView.backgroundColor = [UIColor whiteColor];
    pwdView.userInteractionEnabled = NO;
    pwdView.pwdCount = 7;
    self.pwdView = pwdView;
    [self.view addSubview:pwdView];
//監聽輸入框中輸入的文字   讓自定義的UIView畫圖
#pragma mark UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSString * str = [NSString stringWithFormat:@"%@%@", textField.text, string];
    if (str.length > self.pwdView.pwdCount) {
        [self.pwdTextField setText:[str substringToIndex:self.pwdView.pwdCount]];
        return NO;
    }else{
        if ([string isEqualToString:@""]) {
            [self.pwdView setCount:str.length - 1];
        }else{
            [self.pwdView setCount:str.length];
        }
    }
    return YES;
}

“`
//自定義的UIView 重寫drawRect方法,
-(void)drawRect:(CGRect)rect{

CGContextRef  ctx = UIGraphicsGetCurrentContext();

//畫最外邊的矩形
CGContextSetLineJoin(ctx, kCGLineJoinRound);
CGContextAddRect(ctx, rect);


//分割線
CGFloat gridWidth = rect.size.width/self.pwdCount;
CGFloat gridHeight = rect.size.height;
for (int i = 0; i < self.pwdCount; i++) {
    CGContextMoveToPoint(ctx, gridWidth * (i + 1), 0);
    CGContextAddLineToPoint(ctx, gridWidth * (i + 1), gridHeight);
}
CGContextStrokePath(ctx);

//畫點
CGFloat pointY = rect.size.height/2;
for (int i = 0; i < count1; i++) {
    CGContextAddArc(ctx, gridWidth/2 + i * gridWidth, pointY, 5, 0, M_PI  *2, 1);
    CGContextFillPath(ctx);
}

}
//正常情況下 drawRect只會調用一次 輸入框的文字每變化一次,
//我們就需要調用[self setNeedsDisplay]; 重新執行drawRect方法
- (void)setCount:(NSInteger)count{
count1 = count;
[self setNeedsDisplay];
}

總結:

這種做法只是騙了用戶的眼睛,個人認爲很挫,大家有更好的方法可以和我交流哈!QQ:729376398。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章