Outline UILabel text in UILabel Subclass

后端 未结 6 1922
你的背包
你的背包 2020-12-31 09:52

I\'m trying hard to find a way to simply add an outline/stroke/contour to my UILabel text. Talking about a stroke around the letters of the text not around the background of

6条回答
  •  春和景丽
    2020-12-31 10:27

    Here you have class with implementation, copy and paste to playgrond for test:

        class StrokedLabel: UILabel {
    
            var strockedText: String = "" {
                willSet(newValue) {
                    let strokeTextAttributes = [
                        NSStrokeColorAttributeName : UIColor.black,
                        NSForegroundColorAttributeName : UIColor.white,
                        NSStrokeWidthAttributeName : -4.0,
                        NSFontAttributeName : UIFont.boldSystemFont(ofSize: 30)
                        ] as [String : Any]
    
                    let customizedText = NSMutableAttributedString(string: newValue,
                                                                   attributes: strokeTextAttributes)
    
    
                    attributedText = customizedText
                }
            }
        }
    
    
    //////////// PLAYGROUND IMPLEMENTATION PART /////////
        let text = "Stroked text"
    
    // UILabel subclass initialization
        let label = StrokedLabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
    // simple assign String to 'strockedText' property to see the results
        label.strockedText = text
    
        label.backgroundColor = UIColor.white
    
    
        label
    

    Swift 4.2

    import UIKit
    
    class StrokedLabel: UILabel {
    
    var strockedText: String = "" {
        willSet(newValue) {
            let strokeTextAttributes : [NSAttributedString.Key : Any] = [
                NSAttributedString.Key.strokeColor : UIColor.black,
                NSAttributedString.Key.foregroundColor : UIColor.white,
                NSAttributedString.Key.strokeWidth : -4.0,
                NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 30)
                ] as [NSAttributedString.Key  : Any]
    
            let customizedText = NSMutableAttributedString(string: newValue,
                                                           attributes: strokeTextAttributes)
    
    
            attributedText = customizedText
        }
    }
    
    }
    
    //////////// PLAYGROUND IMPLEMENTATION PART /////////
      let text = "Stroked text"
    
      // UILabel subclass initialization
      let label = StrokedLabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
      // simple assign String to 'strockedText' property to see the results
      label.strockedText = text
    
      label.backgroundColor = UIColor.clear
    
    
      label
    

    Maybe refactoring for this class will be welcomed, but should work for you at this form

    As you can see usage is very convenient.

提交回复
热议问题