Swift 带圆角的彩色文本背景

Swift 带圆角的彩色文本背景,swift,text,background,cornerradius,Swift,Text,Background,Cornerradius,我目前正在使用Swift开发一个iOS应用程序,我需要实现所附图片中显示的文本效果 我有一个标签,其中显示了一些由用户编写的文本,我需要使文本背景角(而不是标签背景)圆角 有办法吗? 我会在网上搜索,但是没有运气 多谢各位 这里有一些代码可以帮助您。我得到的结果和你想要的很相似 class MyTextView: UITextView { let textViewPadding: CGFloat = 7.0 override func draw(_ rect: CGRect)

我目前正在使用Swift开发一个iOS应用程序,我需要实现所附图片中显示的文本效果

我有一个标签,其中显示了一些由用户编写的文本,我需要使文本背景角(而不是标签背景)圆角

有办法吗? 我会在网上搜索,但是没有运气

多谢各位


这里有一些代码可以帮助您。我得到的结果和你想要的很相似

class MyTextView: UITextView {

    let textViewPadding: CGFloat = 7.0

    override func draw(_ rect: CGRect) {
        self.layoutManager.enumerateLineFragments(forGlyphRange: NSMakeRange(0, self.text.count)) { (rect, usedRect, textContainer, glyphRange, Bool) in

            let rect = CGRect(x: usedRect.origin.x, y: usedRect.origin.y + self.textViewPadding, width: usedRect.size.width, height: usedRect.size.height*1.2)
            let rectanglePath = UIBezierPath(roundedRect: rect, cornerRadius: 3)
            UIColor.red.setFill()
            rectanglePath.fill()
        }
    }
}

非常感谢您!我会尽快尝试,并让你知道:)你可以尝试,但我不是十全十美!我已经设法让它在用户按下每个键时都能工作!非常感谢你!