Are there any analogues of [NSString stringWithFormat:] for NSAttributedString

前端 未结 4 1406
后悔当初
后悔当初 2020-12-09 05:14

Usually I build app interface in interface builder. Sometimes design requires to use attributed strings (fonts, colors and etc.). It\'s easy to configure if string is static

4条回答
  •  一向
    一向 (楼主)
    2020-12-09 06:02

    Here is a Swift 4 extension based on TheJeff's answer (corrected for multiple substitutions). It is restricted to substituting placeholders with NSAttributedString's:

    public extension NSAttributedString {
        convenience init(format: NSAttributedString, args: NSAttributedString...) {
            let mutableNSAttributedString = NSMutableAttributedString(attributedString: format)
    
            var nsRange = NSString(string: mutableNSAttributedString.string).range(of: "%@")
            var param = 0
            while nsRange.location != NSNotFound {
                guard args.count > 0, param < args.count else {
                    fatalError("Not enough arguments provided for \(format)")
                }
    
                mutableNSAttributedString.replaceCharacters(in: nsRange, with: args[param])
                param += 1
                nsRange = NSString(string: mutableNSAttributedString.string).range(of: "%@")
            }
    
            self.init(attributedString: mutableNSAttributedString)
        }
    }
    

提交回复
热议问题