我一直在为这个问题寻找好的现有解决方案,但没有成功。
所以我能够自己实现它。
这就是为什么我要自我回答问题以与社区分享知识。
解决方案
NSAttributedString+VPAttributedFormat 类别提供了基于属性格式和应满足此格式的参数构建属性字符串的方法。
使用此类别最合适的情况是在界面生成器中配置了可变属性文本的文本控件。
您需要为属性文本设置正确的字符串格式并配置必要的属性。
然后,您需要使用此类方法在代码中传递必要的参数。
- 格式语法与
[NSString stringWithFormat:]方法中的相同;
- 可用于 Objective C 和 Swift 代码;
- 需要 iOS 6.0 及更高版本;
- 与 CocoaPods 集成;
- 包含单元测试。
用法
1.导入框架头文件或模块
// Objective C
// By header
#import <VPAttributedFormat/VPAttributedFormat.h>
// By module
@import VPAttributedFormat;
// Swift
import VPAttributedFormat
2。在界面生成器中为文本控件设置正确的格式和属性
3.创建 IBOutlet 并将其与文本控件链接
// Objective C
@property (nonatomic, weak) IBOutlet UILabel *textLabel;
// Swift
@IBOutlet weak var textLabel: UILabel!
4.用必要的参数填充格式
// Objective C
NSString *hot = @"Hot";
NSString *cold = @"Cold";
self.textLabel.attributedText = [NSAttributedString vp_attributedStringWithAttributedFormat:self.textLabel.attributedText,
hot,
cold];
// Swift
let hot = "Hot"
let cold = "Cold"
var arguments: [CVarArgType] = [hot, cold]
textLabel.attributedText = withVaList(arguments) { pointer in
NSAttributedString.vp_attributedStringWithAttributedFormat(textLabel.attributedText, arguments: pointer)
}
5.查看结果
示例
VPAttributedFormatExample 是一个示例项目。它提供了 Basic 和 Pro 格式的示例。