Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

自定义构造 Attribute #42

Closed
HParis opened this issue Mar 24, 2022 · 6 comments
Closed

自定义构造 Attribute #42

HParis opened this issue Mar 24, 2022 · 6 comments

Comments

@HParis
Copy link

HParis commented Mar 24, 2022

我的需求是希望能自定义构造字符串差值过程中使用自定义的 attributes

// 构造自定义的 Attribute
extension ASAttributedString.Attribute {
    
    public static func fontStyle(_ value:  UIFont.TextStyle) -> Self {
        let font = UIFont.preferredFont(forTextStyle: value)
        
        let style = NSMutableParagraphStyle()
        style.minimumLineHeight = 20
        style.maximumLineHeight = 20
        
        let baselineOffset = (20 - font.lineHeight) * 0.5

        return .init(attributes: [
            .font: font,
            .paragraphStyle: style,
            .baselineOffset: baselineOffset
        ])
    }
}
// 用法如下:
 """
        \("fontStyle: .sbuheadline", .fontStyle(.subheadline), .background(UIColor.systemBackground), .foreground(UIColor.label))
"""

但是目前由于 Attribute 的 attributes 是 internal 的,导致无法构造自定义的 attributes.

@lixiang1994
Copy link
Owner

其实你可以扩展实现 比如:

public extension Array where Element == ASAttributedString.Attribute {
    
    static var defalut: [ASAttributedString.Attribute] = [
        .font(.systemFont(ofSize: 13)),
        .foreground(.black)
    ]
    
    static let xxxx: [ASAttributedString.Attribute] = []
}

@HParis
Copy link
Author

HParis commented Mar 25, 2022

image

按照上面的扩展实现报错了。

@lixiang1994
Copy link
Owner

\("test", with: .defalut)

@HParis
Copy link
Author

HParis commented Mar 25, 2022

但是这样的话,后面就无法在增加其他 attribute 属性了。

还是希望能实现这样的调用效果:

"""
("fontStyle: .sbuheadline", .fontStyle(.subheadline), .background(.systemBackground), .foreground(.label))
"""

@lixiang1994
Copy link
Owner

\("test", with: .defalut + [.kern(1), .xxxxx])

@HParis
Copy link
Author

HParis commented Mar 25, 2022

嗯嗯,好的。

谢谢!

@HParis HParis closed this as completed Mar 25, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants