LCLabel 是一个基于 TextKit 2 的 UILabel,它模仿了 UITextView 的行为
File -> Swift Packages -> Add Package Dependency
Enter package URL: https://github.com/mustiikhalil/LCLabel
dependencies: [
.package(
name: "LCLabel",
url: "https://github.com/mustiikhalil/LCLabel",
from: "X.Y.Z"),
]
let text = NSMutableAttributedString(
string: "welcome to this new adventure!!!",
attributes: [:])
let range = (text.string as NSString).range(of: "welcome")
text.addAttribute(
.lclabelLink, // Note we use type `lclabelLink`
value: URL(string: "tel://909001")!,
range: range)
let label = LCLabel(
frame: CGRect(
origin: .zero,
size: .init(
width: 300,
height: 30)))
label.isUserInteractionEnabled = true
label.delegate = self
label.attributedText = text
view.addSubview(label)
或者,如果正在使用 AutoLayout
let label = LCLabel(frame: .zero)
label.isUserInteractionEnabled = true
label.delegate = self
label.attributedText = text
view.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
label.topAnchor.constraint(equalTo: view.topAnchor),
label.leadingAnchor.constraint(equalTo: view.leadingAnchor),
label.trailingAnchor.constraint(equalTo: view.trailingAnchor),
label.bottomAnchor.constraint(equalTo: view.bottomAnchor)])
在使用 TextKit 构建它时,虽然很有趣,但也发现以下问题
链接的样式设置通常会失效。这里有两种解决方案:1- 创建 NSAttributedString 时,使用 .lclabelLink
类型而不是 .link
2- 将 linkStyleValidation
设置为 .ensure
,这将强制 NSTextStorage 要么替换所有 .link
的实例为 .lclabelLink
,要么获取 linkAttributes
的值并将其设置为 Storage。
只有当设置了 .ensure
时,才会设置 linkAttributes
。
git clone https://github.com/mustiikhalil/LCLabel
cd LCLabel
open DemoApp/DemoApp.xcodeproj
// or
open package.swift
LCLabel
有三种构建方案
DemoApp
解释了如何使用 LCLabel
DemoApp
可以以三种模式运行,-scrollview
、-autolayout
和 default
。 您需要将参数作为 Arguments Passed On Launch
传递
UI Full Tests
表明 LCLabel 没有任何卡顿 以下是在 iPhone xs 上与 UILabel 基线进行比较的结果
以 UILabel 作为基线,我们能够实现与 UILabel 相似的性能。
一个简单的文本在 LCLabel 中会占用大约 96 Kib
的内存,而 UILabel 也是如此。
单行文本在 LCLabel 中会占用大约 384 Kib
的内存,而 UILabel 也是如此。
带有 Emoji 表情的单行文本在 LCLabel 中会占用大约 1.12 MiB
的内存,而 1.23 MiB
的 UILabel 也是如此。
以 UILabel 作为基线,我们能够在滚动时实现与 UILabel 相似的性能,这在 UI Full Tests
中进行了测量。 基准测试基于在 iPhone XS 上检测到的卡顿数量,当滚动列表大约 5 次时,两个标签都零卡顿。
LCLabel
是 MIT 许可证。
UILabel 和 UITextView 是 Apple 自己的组件。