Search code examples
swiftios13nsshadow

How to make a shadow on iOS13


I set shadow on NSMutableAttributedString, it works on other version of iOS but not iOS 13, the next is my code

let shadow = NSShadow.init()
            shadow.shadowColor = UIColor.red
            shadow.shadowBlurRadius = 20
            
            attr.addAttribute(NSAttributedString.Key.shadow, value: shadow, range: NSRange.init(location: 0, length: (text as NSString).length))

It works well on UILabel attributedText,but not works well on CATextLayer string On iOS13


Solution

  • iOS 14 or later

    let shadow = NSShadow.init()
    shadow.shadowColor = UIColor.red
    shadow.shadowBlurRadius = 20
    attr.addAttribute(NSAttributedString.Key.shadow, value: shadow, range: NSRange.init(location: 0, length: (text as NSString).length))
    subLayer.string = attr
    

    ios 13 or earlier

    let shadow = NSShadow.init()
    shadow.shadowColor = UIColor.red
    shadow.shadowBlurRadius = 20
    attr.addAttribute(NSAttributedString.Key.shadow, value: shadow, range: NSRange.init(location: 0, length: (text as NSString).length))
    
    subLayer.shadowRadius = 20
    subLayer.shadowColor = UIColor.red.cgColor
    subLayer.shadowOpacity = 1
    subLayer.string = attr