如何删除文本的一部分

克里斯·斯科特

我想像这样划破价格。

以 19.99 美元、5.99 美元的价格 购买此课程

请注意只有 19.99 美元的划线是怎么回事?我如何使用 UILabel 和 Swift 做到这一点?

这是我到目前为止所拥有的?

extension String {
    func strikeThrough() -> NSAttributedString {
        let attributeString =  NSMutableAttributedString(string: self)
        attributeString.addAttribute(
            NSAttributedString.Key.strikethroughStyle,
               value: NSUnderlineStyle.single.rawValue,
                   range:NSMakeRange(0,attributeString.length))
        return attributeString
    }
}
pua666

创建属性字符串确实很麻烦。

这个聪明的代码扩展NSAttributedString了一个.composing(_:)方法,我在 GitHub 上找到了它(见底部的版权声明):https : //github.com/vincent-pradeilles/NSAttributedStringBuilder它使用结果构建器nee函数构建器)。

@_functionBuilder
public class NSAttributedStringBuilder {
    public static func buildBlock(_ components: NSAttributedString...) -> NSAttributedString {
        let result = NSMutableAttributedString(string: "")

        return components.reduce(into: result) { (result, current) in result.append(current) }
    }
}

extension NSAttributedString {
    public class func composing(@NSAttributedStringBuilder _ parts: () -> NSAttributedString) -> NSAttributedString {
        return parts()
    }
}

使用此扩展程序,您可以像这样构建属性字符串:

let attributedString = NSAttributedString.composing {
    NSAttributedString(string: "Buy this course for ")
    NSAttributedString(string: "$19.99", attributes: [.strikethroughStyle : NSUnderlineStyle.single.rawValue])
    NSAttributedString(string: ", $5.99")
}

然后,当然,您将属性字符串分配给UILabel'sattributedText属性。

这应该可以用于任何属性。

请注意,它需要针对 Swift 5.3 进行更新(我还没有),因为它早于结果构建器语言功能的最终命名法。所以基本上你需要替换@_functionBuilder@resultBuilder如果我没记错的话。

由于这不是我的代码并且它是在 MIT 许可下发布的,我想我必须在此处重新打印通知:

麻省理工学院执照

版权所有 (c) 2019 Vincent Pradeilles

特此授予任何人免费获得本软件副本和相关文档文件(“软件”)的许可,不受限制地处理本软件,包括但不限于使用、复制、修改、合并的权利、发布、分发、再许可和/或出售软件的副本,并允许向其提供软件的人员这样做,但须符合以下条件:

上述版权声明和本许可声明应包含在软件的所有副本或重要部分中。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章