写一个类似iPhone内置拨号盘上的号码显示Label

来源:互联网 发布:淘宝非法交易如何退货 编辑:程序博客网 时间:2024/05/22 03:31

     iPhone内置的号码盘上有一个显示号码的控件,它看起来似乎有些像Label,又有点像Textfield。类似Textfield,它也会有right View,不同的是,它不会触发键盘,也不会显示光标。那么从实现上讲,把它做成一个Label会更容易。至于right View可以另行加一个按钮或者别的。

    先来研究下这个Label的行为,

(1)长按它之后,会跳出菜单,在没有text的时候,提示可以黏贴;在含有text的时候,可以复制和黏贴。

(2)复制和黏贴的时候,都不能进行选择。

(3)黏贴除“0123456789*+#abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ”之外的字符会被忽略。

(4)黏贴“abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ”会转为键盘上对应的数字。


我们要自定义一个Label,姑且叫它“MCMenuLabel”,继承自UILabel。

接着实现如下方法:

// default is NO- (BOOL)canBecomeFirstResponder{    return YES;}//implement for copy behaviour-(void)copy:(id)sender{    UIPasteboard *pboard = [UIPasteboard generalPasteboard];    pboard.string = self.text;}//implement for paste behaviour- (void)paste:(id)sender {    UIPasteboard *pboard = [UIPasteboard generalPasteboard];    NSString *resultString = [self smartTranslation:pboard.string];    self.text = resultString;}-(BOOL)canPerformAction:(SEL)action withSender:(id)sender{    if (([self.text length]>0&&action == @selector(copy:))||action == @selector(paste:)) {        return YES;    }    return NO;}

最关键的一个smartTranslation:方法,用于对黏贴的字符进行过滤以及映射。

#pragma mark - utils function- (NSString *)smartTranslation:(NSString *)string{ //   NSString *filter = [[string componentsSeparatedByCharactersInSet: //                         [[NSCharacterSet characterSetWithCharactersInString:VALID_NUMBER_CHARS] invertedSet]] //                        componentsJoinedByString:@""];    NSMutableString *mapper = [NSMutableString string];    for (int i = 0; i < [string length]; i++) {        unichar curChar = [string characterAtIndex:i];        if ( curChar >= '0' && curChar <= '9') {            [mapper appendString:[NSString stringWithFormat:@"%C",curChar]];        }else if (curChar == '*' || curChar == '+'|| curChar == '#'){            [mapper appendString:[NSString stringWithFormat:@"%C",curChar]];        }else{            int distance = 0;            if (curChar >= 'A' && curChar <= 'Z'){                distance = curChar - 'A';                            }else if (curChar >= 'a' && curChar <= 'z'){                distance = curChar - 'a';            }else                continue;//protect            int map = distance / 3;            if (distance == 18 || distance == 21) {                map += 1;            }else{                map += 2;            }            if (map > 9) {                map = 9;            }            [mapper appendString:[NSString stringWithFormat:@"%d",map]];        }    }    return mapper;}

完整的测试用的工程,在github上。


0 0
原创粉丝点击