LabelConfigurator
LabelConfigurator是一个用于iOS的紧凑型库,用于帮助配置UILabels,无需在设置多个步骤中设置所有文本属性,尤其是在具有不同属性的子字符串时。
它使用Builder模式创建,允许向单个标签添加多个属性,但只需要在需要时一次性设置所有属性。接口很简单且直观,使得该库的采用速度非常快。有关更详细的示例,请参阅使用部分。
要求
使用LabelConfigurator
所需的最小要求如下
- iOS 9.0
- Xcode 8
- 与Obj-C和Swift兼容
安装
CocoaPods
您可以使用CocoaPods将LabelConfigurator
添加到您的项目中。为了安装它,只需在您的Podfile中指定即可。
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'
use_frameworks!
target 'TargetName' do
pod 'LabelConfigurator', '~> 0.3.0'
end
在Podfile中指定新的依赖项后,只需运行pod install
确保安装最新版本的库。
Carthage
Carthage是一个去中心化的依赖项管理器,它构建您依赖项并为您提供二进制框架。
要使用Carthage将LabelConfigurator
集成到Xcode项目中,请指定它在您的Cartfile
中。
github "fabioameida/LabelConfigurator" ~> 0.3.0
运行carthage update
以构建框架,并将构建的LabelConfigurator.framework
拖放到您的Xcode项目中。
使用
要将库导入到项目中,只需将以下行添加到您的Swift文件中
import LabelConfigurator
如果您想为标签添加一个真正的简单UIFont和文字颜色,只需添加以下代码
self.myLabel.setLabelText("Some text")
.set(font: UIFont.boldSystemFont(ofSize: 14))
.set(textColor: .blue)
.configure()
请注意前一段代码的两个重要方面
- 被调用的第一个方法是
setLabelText()
,它返回UILabelBuilder
,允许您在不使用任何模板代码的情况下添加所有必要的属性到UILabel中; - 添加所有属性后,只需在最后调用
configure()
,这将将所有定义的属性应用到UILabel。
以上代码可能看起来与您用来仅更改字体和文字颜色的UIKit代码非常相似。但当涉及到其他常见情况,如设置自定义Font Tracking或Line Spacing时,情况就不同了,因为这会涉及创建一个NSAttributedString。
要使用LabelConfigurator
实现这一点,您只需做以下操作
self.myLabel.setLabelText("Some text \n Other text")
.set(font: UIFont.boldSystemFont(ofSize: 14))
.set(textColor: .blue)
.set(fontTracking: 4)
.set(lineSpacing: 10)
.configure()
另一个常见示例是在子字符串中添加不同的文本属性。现在,您可以这样操作
let minimumAmount = "$5"
self.myLabel.setLabelText("Please donate \(minimumAmount) or more!")
.set(font: UIFont.systemFont(ofSize: 12))
.set(textColor: .black)
.set(font: UIFont.boldSystemFont(ofSize: 13), onSubstring: minimumAmount)
.set(textColor: .red, onSubstring: minimumAmount)
.configure()
高级使用
在
但是,并没有涵盖所有可能性(我们想要保持这种状态),包括在
好处是,您可以使用两种便捷方法将您想要的任何自定义属性添加到
func set(attribute: NSAttributedStringKey, value: Any, onSubstring substring: String)
func set(attribute: NSAttributedStringKey, value: Any, onRange range: NSRange)
例如,如果您想将删除线属性添加到
let oldPrice = "$350"
let newPrice = "$299"
self.myLabel.setLabelText("New price \(oldPrice) \(newPrice)")
.set(font: UIFont.systemFont(ofSize: 12))
.set(textColor: .black)
.set(textColor: .red, onSubstring: newPrice)
.set(textColor: .lightGray, onSubstring: oldPrice)
.set(attribute: NSAttributedStringKey.strikethroughStyle, value: 1, onSubstring: oldPrice)
.configure()
所有这些示例都可以在“示例”项目中找到。
作者
如果您想联系我,请在twitter上找到我:@fabioacalmeida
许可
LabelConfigurator 在MIT许可下可用。有关更多信息,请参阅LICENSE文件。