JKAttributedString 0.2.0

JKAttributedString 0.2.0

测试测试过
语言语言 SwiftSwift
授权协议 MIT
发布日期最后发布2017年10月
SwiftSwift 版本3.2
SPM 支持 SPM

Junmo Kim 维护。



JKAttributedString 提供了 NSAttributedString 的 Swift API。

在 Swift 的值类型世界中使用 NSAttributedStringNSMutableAttributedString 疲倦了吗?
这使得处理属性字符串和 String 一样简单。

特性

  • 值类型属性字符串
  • 类型化属性
  • 简单的拼接
  • 基于字符的范围(不是基于 UTF-16 的 NSRange!)
  • UTF-16 和字符之间的范围转换器
  • 支持自定义属性

如何使用

基本用法

var aString = JKAttributedString(string: "Whatever",
                                 attributes: [.color(.gray), .font(.systemFont(ofSize: 12))])
aString.adding(attributes: [.color(.red)])  // Red "Whatever"

let bString = "Want".attributed([.font(.systemFont(ofSize: 20))])  // Size 20
// bString.adding( ... )  <- COMPILE ERROR

let cString = aString + " You " + bString
// Whatever You { color: red, size: 12 }Want{ size: 20 }

let dString = "Whenever You " + bString  // Size 20

let testString = "Doing 테스트 ".attributed([.color(.gray)])
    + "🎯 です。¶".attributed([.color(.blue)])
testString.attributes(at: testString.index(testString.startIndex, offsetBy: 9)) // Gray
testString.attributes(at: testString.index(testString.startIndex, offsetBy: 10)) // Blue

自定义属性类型

enum SystemFontAttribute: JKAttributeType {
    case normal(CGFloat)
    case bold(CGFloat)
    
    var name: String {
        return NSFontAttributeName
    }
    
    var value: Any {
        switch self {
        case .normal(let size):
            return UIFont.systemFont(ofSize: size)
        case .bold(let size):
            return UIFont.boldSystemFont(ofSize: size)
        }
    }
}

let systemString = "System".attributed([SystemFontAttribute.bold(20)])