UILabel 的直接替代品,支持话题标签 (#)、提及 (@)、URL (http://)、电子邮件和自定义正则表达式模式,使用 Swift 编写
UILabel
的直接替代品工作将以下内容添加到您的 Cartfile
并按照 这些说明 操作
github "optonaut/ActiveLabel.swift"
CocoaPods 0.36 添加了对 Swift 和嵌入式框架的支持。要将 ActiveLabel 集成到您的项目中,请将以下内容添加到您的 Podfile
platform :ios, '10.0'
use_frameworks!
pod 'ActiveLabel'
import ActiveLabel
let label = ActiveLabel()
label.numberOfLines = 0
label.enabledTypes = [.mention, .hashtag, .url, .email]
label.text = "This is a post with #hashtags and a @userhandle."
label.textColor = .black
label.handleHashtagTap { hashtag in
print("Success. You just tapped the \(hashtag) hashtag")
}
let customType = ActiveType.custom(pattern: "\\swith\\b") //Regex that looks for "with"
label.enabledTypes = [.mention, .hashtag, .url, .email, customType]
label.text = "This is a post with #hashtags and a @userhandle."
label.customColor[customType] = UIColor.purple
label.customSelectedColor[customType] = UIColor.green
label.handleCustomTap(for: customType) { element in
print("Custom type tapped: \(element)")
}
默认情况下,ActiveLabel 实例具有以下配置
label.enabledTypes = [.mention, .hashtag, .url, .email]
但请随意启用/禁用以满足您的需求
当使用 ActiveLabel 时,建议使用 customize(block:)
方法进行自定义。原因是 ActiveLabel 会对您设置的每个属性做出反应。因此,如果您设置 3 个属性,textContainer 将刷新 3 次。
当使用 customize(block:)
时,您可以将标签上的所有自定义分组,这样 ActiveLabel 只会刷新 textContainer 一次。
示例
label.customize { label in
label.text = "This is a post with #multiple #hashtags and a @userhandle."
label.textColor = UIColor(red: 102.0/255, green: 117.0/255, blue: 127.0/255, alpha: 1)
label.hashtagColor = UIColor(red: 85.0/255, green: 172.0/255, blue: 238.0/255, alpha: 1)
label.mentionColor = UIColor(red: 238.0/255, green: 85.0/255, blue: 96.0/255, alpha: 1)
label.URLColor = UIColor(red: 85.0/255, green: 238.0/255, blue: 151.0/255, alpha: 1)
label.handleMentionTap { self.alert("Mention", message: $0) }
label.handleHashtagTap { self.alert("Hashtag", message: $0) }
label.handleURLTap { self.alert("URL", message: $0.absoluteString) }
}
您可以设置 URL 可以拥有的最大长度;
label.urlMaximumLength = 30
从现在开始,大于该长度的 URL 将被裁剪。
https://afancyurl.com/whatever
-> https://afancyurl.com/wh...
label.handleMentionTap { userHandle in print("\(userHandle) tapped") }
label.handleHashtagTap { hashtag in print("\(hashtag) tapped") }
label.handleURLTap { url in UIApplication.shared.openURL(url) }
label.handleEmailTap { email in print("\(email) tapped") }
label.handleCustomTap(for: customType) { element in print("\(element) tapped") }
label.filterHashtag { hashtag in validHashtags.contains(hashtag) }
label.filterMention { mention in validMentions.contains(mention) }
在编写 ActiveLabel
之前,我们尝试了很多以下替代方案,但对质量水平或易用性不太满意,因此我们决定贡献我们自己的解决方案。