2017-07-25 153 views
2

當我使用中風和陰影時,我會得到某種雙擊。我怎樣才能解決這個問題?iOS上的NSAttributedString陰影和描邊?

遊樂場代碼:

import UIKit 

var shadow = NSShadow() 
shadow.shadowColor = UIColor.black 
shadow.shadowOffset = CGSize(width: 0, height: 3) 

class CustomLabel: UILabel { 
    override func drawText(in rect: CGRect) { 
     let attributes: [String: Any] = [NSStrokeWidthAttributeName: -2.0, 
          NSStrokeColorAttributeName: UIColor.black, 
          NSForegroundColorAttributeName: UIColor.white, 
          NSShadowAttributeName: shadow, 
          NSFontAttributeName: UIFont(name: "AvenirNext-Bold", size: 50)] 
     self.attributedText = NSAttributedString(string: self.text ?? "", attributes: attributes) 
     super.drawText(in: rect) 
    } 
} 

let label = CustomLabel(frame: CGRect(x: 0, y: 0, width: 200, height: 100)) 
label.backgroundColor = UIColor.orange 
label.text = "Hello" 

結果:

enter image description here

回答

1

我想通了。如果我將陰影應用於標籤的CALayer的,並禁用背景色,它按預期工作:

import UIKit 

class CustomLabel: UILabel { 

    required init?(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder) 
    } 

    override init(frame: CGRect) { 
     super.init(frame: frame) 
     self.layer.shadowColor = UIColor.black.cgColor 
     self.layer.shadowOffset = CGSize(width: 0, height: 3) 
     self.layer.shadowOpacity = 1.0 
     self.layer.shadowRadius = 0.0 
    } 

    override func drawText(in rect: CGRect) { 
     let attributes: [String: Any] = [NSStrokeWidthAttributeName: -2.0, 
             NSStrokeColorAttributeName: UIColor.black, 
             NSForegroundColorAttributeName: UIColor.white, 
             NSFontAttributeName: UIFont(name: "AvenirNext-Bold", size: 50)] 
     self.attributedText = NSAttributedString(string: self.text ?? "", attributes: attributes) 
     super.drawText(in: rect) 
    } 
} 

let label = CustomLabel(frame: CGRect(x: 0, y: 0, width: 200, height: 100)) 
label.text = "Hello" 

enter image description here