ios - 是否有 [NSString stringWithFormat :] for NSAttributedString 的任何类似物

标签 ios objective-c swift nsattributedstring

通常我在界面生成器中构建应用程序界面。有时设计需要使用属性字符串(字体、颜色等)。如果字符串是静态的,配置起来很容易。
但是,如果字符串是动态的(带参数的格式),则无法在界面构建器中配置属性。需要写很多代码。
我正在为 NSAttributedString 寻找一些 [NSString stringWithFormat:] 的类似物。所以我将能够在界面生成器中设置字符串格式和必要的属性,然后在代码中提供必要的参数。

例如:
让我们考虑一下我需要这样格式的显示字符串:“%d + %d = %d”(所有数字都是粗体)。< br/> 我想在界面生成器中配置这种格式。在代码中,我想提供参数:1、1、2。应用程序应显示“1 + 1 = 2”。

最佳答案

兼容 Swift 4.2

public extension NSAttributedString {
    convenience init(format: NSAttributedString, args: NSAttributedString...) {
        let mutableNSAttributedString = NSMutableAttributedString(attributedString: format)

        args.forEach { (attributedString) in
            let range = NSString(string: mutableNSAttributedString.string).range(of: "%@")
            mutableNSAttributedString.replaceCharacters(in: range, with: attributedString)
        }
        self.init(attributedString: mutableNSAttributedString)
    }
}

用法:

let content = NSAttributedString(string: "The quick brown %@ jumps over the lazy %@")
let fox = NSAttributedString(string: "fox", attributes: [.font: Fonts.CalibreReact.boldItalic.font(size: 40)])
let dog = NSAttributedString(string: "dog", attributes: [.font: Fonts.CalibreReact.lightItalic.font(size: 11)])
attributedLabel.attributedText = NSAttributedString(format: content, args: fox, dog)

结果:

enter image description here

关于ios - 是否有 [NSString stringWithFormat :] for NSAttributedString 的任何类似物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31524874/

相关文章:

ios - BLE后台扫描iOS

ios - 自定义单元格文本字段索引在滚动时发生变化

ios - swift 类中的 AWS 配置行导致线程 1 : EXC_BAD_INSTRUCTION

arrays - Swift 字典中的数组

c# - Xamarin.iOS 中的静音

ios - 为什么Objective-C中的BOOL类型是char?

iphone - 在 Objective-C 中获取下周六的日期?

swift - 试图了解构造函数和不同参数类型如何在 Swift 的类内部工作

ios - UISwipeGestureRecognizer 没有可见的接口(interface)声明选择器 'touchesMoved:withEvent:'

iphone - 弹出窗口的屏幕截图不清晰