ios - NSAttributed 文本在 iOS 中带有一条线和一些角度

标签 ios swift swift4 line nsattributedstring

我想在 swift 4 中画一条删除线,如下图所示。

enter image description here

我使用以下代码绘制了删除线,如下图所示。

enter image description here

func strikeThrough(_ color: UIColor) -> NSAttributedString {
    let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: self)
    let textRange = NSRange(location: 0, length: attributeString.length)
    attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 1, range: textRange)
    attributeString.addAttribute(NSAttributedString.Key.baselineOffset, value: 0, range: textRange)
    attributeString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.lightGray, range: textRange)
    attributeString.addAttribute(NSAttributedString.Key.strikethroughColor, value: color, range: textRange)

    return attributeString
}

关于如何在文本上绘制斜线的任何建议。 如果可能,给我一个使用 Core Graphics 的解决方案。

最佳答案

将 UIBezierPath 与您的 UILabel 一起使用,我们将其命名为标签:

        var aPath = UIBezierPath()
        aPath.moveToPoint(CGPoint(x: label.frame.origin.x , y:label.frame.origin.y  - 10)
        aPath.addLineToPoint(CGPoint(x: label.frame.origin.x + label.frame.size.width, y: label.frame.origin.y + label.frame.size.height + 10))
        aPath.closePath()
        UIColor.redColor().set()
        aPath.stroke()

随意玩点数的来源以获得想要的结果。也玩 label.layer.addSublayer(aPath)

关于ios - NSAttributed 文本在 iOS 中带有一条线和一些角度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55338027/

相关文章:

text - 使用 Swift 更改文本颜色

ios - 将 child 添加到 firebase (iOS) - 新 child 的插入不会停止

ios - Self Sizing CollectionView inside a Self Sizing TableViewCell

iphone - NSDocumentDirectory如何工作?

ios - Swift 语言多播委托(delegate)

ios - 如何检测 iOS 11 中的 UIWebview 下降?

iOS生成随机消息

iOS - 对 View 中的多个 Tableview 或 Collectionview 使用/传递手势识别器(Swift)

swift - 如何在 swift 中向 NSArray 添加 nil 值?

ios - 无法分配给属性 : 'item' is a 'let' constant (Swift 4)