银行卡号分割

2018-10-29  本文已影响16人  Luyc_Han
image.png
//
//  DemoTextFiled.m
//  CaseDemo
//
//  Created by xxx on 2018/10/29.
//  Copyright © 2018 Mr.H. All rights reserved.
//

#import "DemoTextFiled.h"

@interface DemoTextFiled ()
/** <#statements#> */
@property (nonatomic,assign) NSUInteger separatedInterval;
@end

@implementation DemoTextFiled

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.separatedInterval = 4;
        // 利用KVO 监听TextFeild的输入变化,但是当文字变化时,观测者没有响应,
        //只用当 textField.text = @"1234" 的时候,才会响应
        [self addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew context:nil];
        //这个是每当TextFeild的输入变化时,会响应
        [self addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventAllEditingEvents];
    }
    return self;
}

-(void)valueChanged:(UITextField*)tf{
    UITextRange * editRange = self.selectedTextRange;
    if ((tf.text != nil) && (tf.text.length>self.separatedInterval) ) {
        NSMutableAttributedString * string =[[NSMutableAttributedString alloc]initWithString:tf.text];
        for (int i = 1; i < tf.text.length; i ++) {
            if ( i %self.separatedInterval == 0) {
                [string addAttribute:NSKernAttributeName
                               value:[NSNumber numberWithFloat:10.f]
                               range:NSMakeRange(i-1, 1)];  
            }
        }
        self.attributedText = string;
        self.selectedTextRange = editRange;
    }
}
@end
上一篇下一篇

猜你喜欢

热点阅读