Custom Label Effects in Swift 4

How to make custom UILabel Effects in Swift ? | Label Extension?

Source -pexels.com

Creating the custom label effects in your application it’s not a big deal you can easily make it your own way here I am showing you few examples of UILabel extension. It’s pretty easy to use to make any label custom without the use of any Custom class and within very less and reusable code.

Make Custom label for OutLine effect

let strokeTextAttributes = [ 
NSAttributedStringKey.strokeColor : UIColor.red,
NSAttributedStringKey.foregroundColor : UIColor.white,
NSAttributedStringKey.strokeWidth : -4.0,
NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 30)]
as [NSAttributedStringKey : Any]
//Making outline here
labelOutLine.attributedText = NSMutableAttributedString(string: “Your outline text”, attributes: strokeTextAttributes)
Label with Outline and foreground colour effects

Make Custom label for UnderLine effect

let attributedString = NSMutableAttributedString(string: “Your UnderLine text”)
attributedString.addAttribute(NSAttributedStringKey.underlineStyle, value: NSUnderlineStyle.styleSingle.rawValue, range: NSRange(location: 0, length: attributedString.length))
//Underline effect here
labelUnderLine.attributedText = attributedString
Underline UILabel Effects

Extension for UILabel

If you use above code for make underline and outline effects then need to use everywhere same code then it doesn’t make any sense. So we can reuse this code by making simple extension function. It’s very easy to use every time to giving effects to any UILabel.

extension UILabel{

func makeOutLine(oulineColor: UIColor, foregroundColor: UIColor{
let strokeTextAttributes = [
NSAttributedStringKey.strokeColor : oulineColor,
NSAttributedStringKey.foregroundColor : foregroundColor,
NSAttributedStringKey.strokeWidth : -4.0,
NSAttributedStringKey.font : self.font
] as [NSAttributedStringKey : Any]
self.attributedText = NSMutableAttributedString(string: self.text ?? "", attributes: strokeTextAttributes)
}

func underline() {
if let textString = self.text {
let attributedString = NSMutableAttributedString(string: textString) attributedString.addAttribute(NSAttributedStringKey.underlineStyle, value: NSUnderlineStyle.styleSingle.rawValue, range: NSRange(location: 0, length: attributedString.length))
            attributedText = attributedString
}
}
}

Check here how to use this extension -
Extension uses in project
You can find full project code from here. Only you need to drag and drop ExUILabel.swift inside your project.

Conclusion

Extension are very useful in Swift programming we can make easily for any existing class, structure, enumeration, or protocol type.😊 🎉


Thank you !

If you having any query regarding this tutorial ? Twitter me: @Anand