对于 iOS 7,这是一个简单易用的 UILabel 补丁,可提供自动颜色检测。
此外
您可以设置自动前景色检测
@property (nonatomic, assign, getter = isAutomaticForegroundColorDetectionEnabled) IBInspectable BOOL automaticForegroundColorDetectionEnabled;
@property (nonatomic, strong) IBInspectable UIColor *skipColorForAutomaticDetection;
这意味着如果您的字符串具有属性,MZSelectableLabel 将为您自动检测所有范围。您甚至可以跳过默认颜色的检测,例如 [UIColor blackColor]
。
[self.label setSelectableRange:[[self.label.attributedText string] rangeOfString:@"Tap me"] hightlightedBackgroundColor:[UIColor colorWithWhite:0.3 alpha:0.3]];
self.label.selectionHandler = ^(NSRange range, NSString *string) {
NSString *message = [NSString stringWithFormat:@"You tapped %@", string];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Hello"
message:message
delegate:nil
cancelButtonTitle:@"Dismiss"
otherButtonTitles:nil];
[alert show];
};
Repository includes MZSelectableLabel that shows a simple use of the label in a storyboard with examples for implementing tappable links.
The demo also demonstrates how to use a gesture recognizer with the label to implement a long press on a link, which uses the rangeValueAtLocation method.
MZSelectableLabel 需要 iOS 7.x 及以上版本。