UITextView

时间:2016-08-17 15:22:11

标签: ios swift uitextview nsattributedstring

我希望UITextView的顶行与文本的其他部分颜色不同,但我没有看到这样做的方法。我看到我可以在添加文本时为文本添加属性文本特征,但是当我添加更多文本时它不会排列。

此外,我尝试通过以下代码创建此效果,但它无法正常工作

if let containerView = textView.superview {
    let gradient = CAGradientLayer(layer: containerView.layer)
    gradient.frame = containerView.bounds
    gradient.colors = [UIColor.clearColor().CGColor, UIColor.blueColor().CGColor]
    gradient.startPoint = CGPoint(x: 0.0, y: 1.0)
    gradient.endPoint = CGPoint(x: 0.0, y: 0.85)
    containerView.layer.mask = gradient
}

1 个答案:

答案 0 :(得分:0)

尝试一下,注释在代码中:

class ViewController: UIViewController, UITextViewDelegate {
    @IBOutlet weak var textView: UITextView!

    // Attributes for the first line. Here we set it to blue
    let firstLineAttributes = [
        NSForegroundColorAttributeName: UIColor.blueColor(),
        NSFontAttributeName: UIFont.systemFontOfSize(14)
    ]

    override func viewDidLoad() {
        super.viewDidLoad()
        self.textView.delegate = self
    }

    // The intial highlight of the first line
    override func viewDidAppear(animated: Bool) {
        textViewDidChange(self.textView)
    }

    func textViewDidChange(textView: UITextView) {
        // Get the range of the chacrters on the first line
        var firstLineRange = NSMakeRange(NSNotFound, 0)
        withUnsafeMutablePointer(&firstLineRange) {
            textView.layoutManager.lineFragmentRectForGlyphAtIndex(0, effectiveRange: $0)
        }

        guard firstLineRange.location != NSNotFound && firstLineRange.length > 0 else {
            return
        }

        let textStorage = textView.textStorage

        // Remove color for the whole UITextView
        // You should call as many `removeAttribute` as needed to udno the attributes set in `firstLineAttributes`
        textStorage.removeAttribute(NSForegroundColorAttributeName, range: NSMakeRange(0, textView.text.characters.count))

        // Set attributes for the first line
        textStorage.setAttributes(self.firstLineAttributes, range: firstLineRange)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        //Dispose of resources that can be re created.
    }
}