2016-08-17 4 views
1

Я хочу, чтобы верхняя строка UITextView была другого цвета, чем остальная часть текста, но я не вижу способа сделать это. Я вижу, что я могу добавить атрибутные текстовые характеристики для текста, когда я его добавляю, но затем он не будет выстраиваться в линию, когда я добавлю больше текста.Имеют разный цвет текста для верхней строки 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 
} 
+0

показать вашу кодирования для ответа – user3182143

+0

define не будет выстраиваться в линию – Sethmr

ответ

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. 
    } 
} 

 Смежные вопросы

  • Нет связанных вопросов^_^