FRHyperLabel 是 UILabel 的一个子类,它让您能够轻松地为一个或多个标签文本添加一个或多个超链接。使用 FRHyperLabel,您可以以非常简单的方式定义不同超链接的样式、处理程序和突出显示外观。
#####CocoaPods
pod 'FRHyperLabel'
定义一组超链接的代码可以短到只有一个语句,只需使用 API:setLinkForSubstring:withLinkHandler:
,它接受一个子串和一个点击处理程序作为输入,并使用元素触摸反馈设置链接。
//Step 1: Define a normal attributed string for non-link texts
NSString *string = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque quis blandit eros, sit amet vehicula justo. Nam at urna neque. Maecenas ac sem eu sem porta dictum nec vel tellus.";
NSDictionary *attributes = @{NSFontAttributeName: [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline]};
label.attributedText = [[NSAttributedString alloc]initWithString:string attributes:attributes];
//Step 2: Define a selection handler block
void(^handler)(FRHyperLabel *label, NSString *substring) = ^(FRHyperLabel *label, NSString *substring){
NSLog(@"Selected: %@", substring);
};
//Step 3: Add link substrings
[label setLinksForSubstrings:@[@"Lorem", @"Pellentesque", @"blandit", @"Maecenas"] withLinkHandler:handler];
@property (nonatomic) NSDictionary *linkAttributeDefault;
@property (nonatomic) NSDictionary *linkAttributeHighlight;
这两个字典指定了不同状态的链接的默认属性。
- (void)setLinkForRange:(NSRange)range withAttributes:(NSDictionary *)attributes andLinkHandler:(void (^)(FRHyperLabel *label, NSRange selectedRange))handler;
通过给出链接子串的范围、正常状态的所需属性和选择处理程序来添加一个链接。
- (void)setLinkForRange:(NSRange)range withLinkHandler:(void(^)(FRHyperLabel *label, NSRange selectedRange))handler;
与 setLinkForRange:withAttributes:andLinkHandler:
相同,但预期这将使用 linkAttributeDefault
填充属性参数。
- (void)setLinkForSubstring:(NSString *)substring withAttribute:(NSDictionary *)attribute andLinkHandler:(void(^)(FRHyperLabel *label, NSString *substring))handler;
通过给出链接子串、正常状态的所需属性和选择处理程序来添加一个链接。这将只为子串的第一次出现添加链接。如果您需要为其他添加链接,请使用 setLinkForRange:withAttributes:andLinkHandler:
。
- (void)setLinkForSubstring:(NSString *)substring withLinkHandler:(void(^)(FRHyperLabel *label, NSString *substring))handler;
与 setLinkForSubstring:withAttributes:andLinkHandler:
相同,但预期这将使用 linkAttributeDefault
填充属性参数。
- (void)setLinksForSubstrings:(NSArray *)substrings withLinkHandler:(void(^)(FRHyperLabel *label, NSString *substring))handler;
通过给出子串数组来添加一组链接。选择处理程序必须是数组中所有链接相同的,只有第一次出现将受到关注。
请参阅维基中的 已知问题 页面。