对于UITextView的顶行有不同的文本颜色
问题描述:
我想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
}
答
试试这个,注释代码:
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.
}
}
显示您的编码回答 – user3182143
定义不会排队 – Sethmr