SwiftResponsiveLabel
一个对指定模式进行响应的 UILabel 子类。它有以下功能
- 它可以检测正则表达式指定的模式,并应用其他样式,如字体、颜色等。
- 它可以替换默认的省略号以可点击的字标配置来标记截断
- 提供了方便的方法来检测哈希标签、用户名处理程序和 URL
安装
请将以下行添加到您的 pod 文件中
pod 'SwiftResponsiveLabel', '2.3'
用法
以下片段解释了公共方法的用法。这些示例假定 ResponsiveLabel 的实例为 "customLabel"。
import SwiftResponsiveLabel
在界面构建器中,将 UILabel 的自定义类设置为 SwiftResponsiveLabel。
用户名处理检测
let userHandleTapAction = PatternTapResponder{ (tappedString)-> (Void) in
let messageString = "You have tapped user handle:" + tappedString
self.messageLabel.text = messageString
}
let dict = [NSForegroundColorAttributeName: UIColor.greenColor(),
NSBackgroundColorAttributeName: UIColor.blackColor()]
self.customLabel.enableUserHandleDetection([NSForegroundColorAttributeName:UIColor.grayColor(),
RLHighlightedAttributesDictionary: dict, RLTapResponderAttributeName:userHandleTapAction])
URL 检测
let URLTapAction = PatternTapResponder{(tappedString)-> (Void) in
let messageString = "You have tapped URL: " + tappedString
self.messageLabel.text = messageString
}
self.customLabel.enableURLDetection([NSForegroundColorAttributeName:UIColor.blueColor(), RLTapResponderAttributeName:URLTapAction])
哈希标签检测
let hashTagTapAction = PatternTapResponder { (tappedString)-> (Void) in
let messageString = "You have tapped hashTag:" + tappedString
self.messageLabel.text = messageString
}
let dict = [NSForegroundColorAttributeName: UIColor.redColor(), NSBackgroundColorAttributeName: UIColor.blackColor()]
customLabel.enableHashTagDetection([RLHighlightedAttributesDictionary : dict, NSForegroundColorAttributeName: UIColor.cyanColor(),
RLTapResponderAttributeName:hashTagTapAction])
自定义截断令牌
将属性字符串设置为截断令牌
let action = PatternTapResponder {(tappedString)-> (Void) in
print("You have tapped token string")
}
let dict = [RLHighlightedBackgroundColorAttributeName:UIColor.blackColor(),
RLHighlightedForegroundColorAttributeName:UIColor.greenColor(), RLTapResponderAttributeName:action]
let token = NSAttributedString(string: "...More", attributes: [NSFontAttributeName: customLabel.font,
NSForegroundColorAttributeName:UIColor.brownColor(), RLHighlightedAttributesDictionary: dict])
customLabel.attributedTruncationToken = token
将图片设置为截断令牌
图片的大小高度应与字体高度大致相等或更小,否则图片将无法正确渲染
let action = PatternTapResponder {(tappedString)-> (Void) in
print("You have tapped token image")
}
self.customLabel.setTruncationIndicatorImage(UIImage(named: "check")!, withSize: CGSize(width: 20.0, height: 20.0), andAction: action)
从界面构建器设置
屏幕截图
参考文献
SwiftResponsiveLabel 的底层实现基于 KILabel (https://github.com/Krelborn/KILabel)。SwiftResponsiveLabel 设计得非常灵活,以便检测正则表达式指定的任何模式。
以下文章有助于增强功能。