How to apply text shadow to UITextView?

前端 未结 7 1078
醉梦人生
醉梦人生 2021-02-06 21:12

Actually I love UILabel. They\'re sweet. Now I had to go to UITextView because UILabel is not aligning text vertically to the top. Damn. O

7条回答
  •  渐次进展
    2021-02-06 21:46

    This Swift example uses the attributed string method of adding shadow to text. See this answer for more about attributed strings in Swift. This method (as opposed to using the layer method) gives you the flexibility to set the shadow on a range of text if you want to.

    // Create a string
    let myString = "Shadow"
    
    // Create a shadow
    let myShadow = NSShadow()
    myShadow.shadowBlurRadius = 3
    myShadow.shadowOffset = CGSize(width: 3, height: 3)
    myShadow.shadowColor = UIColor.gray
    
    // Create an attribute from the shadow
    let myAttribute = [ NSAttributedStringKey.shadow: myShadow ]
    
    // Add the attribute to the string
    let myAttrString = NSAttributedString(string: myString, attributes: myAttribute)
    
    // set the attributed text on a label
    myLabel.attributedText = myAttrString // can also use with UITextView
    

    Updated for Swift 4

提交回复
热议问题