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

は定義されません – 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. 
    } 
} 
関連する問題