Last Updated: February 25, 2016
· bahlor

Some simple Swift Extensions (Strip HTML, RGB Color, Color invert, Dismiss modal segue)

Swift Extensions

Just some very simple extension I use in some of my projects, nothing special.

NSString / String stripHTML()

This simple extension allows to strip HTML out of a string and returns the plain text. It does NOT convert the text to attributed text.

The Extension:

The html replacement regular expression
let     htmlReplaceString   :   String  =   "<[^>]+>"

extension NSString {
    Takes the current NSString object and strips out HTML using regular expression. All tags get stripped out.

    :returns: NSString html text as plain text
    func stripHTML() -> NSString {
        return self.stringByReplacingOccurrencesOfString(htmlReplaceString, withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range: NSRange(location: 0,length: self.length)) as NSString

extension String {
    Takes the current String struct and strips out HTML using regular expression. All tags get stripped out.

    :returns: String html text as plain text
    func stripHTML() -> String {
        return self.stringByReplacingOccurrencesOfString(htmlReplaceString, withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range: nil)

An example:

let myNSString  :   NSString    =   NSString(string: "<html><head><title>Test</title></head><body></body></html>")
let myString    :   String      =   "<html><head><title>Test</title></head><body></body></html>"

myNSString.stripHTML() // Returns "test"

myString.stripHTML() // Returns "test"

UIColor rgb / invert

As web developer I'm quite used to write colors as hex values like #990000 or similar. But using those in swift out of the box is not as easy as it might seem. Its not implemented anymore. So I created a minimalistic extension of UIColor that allows to create a UIColor using a hex color value.

Additionally I needed to be able to invert colors, so I also created a color extension that inverts the currently used color and returns a new inverted color.

The Extension:

extension UIColor {
    An additional convenience initializer function that allows to init a UIColor object using a hex color value.

    :param: rgb UInt color hex value (f.e.: 0x990000 for a hex color code like #990000)
    :param: alpha Double Optional value that sets the alpha range 0=invisible / 1=totally visible

    convenience init(rgb: UInt, alpha: Double = 1.0) {
            red:    CGFloat((rgb    & 0xFF0000) >> 16) / 255.0,
            green:  CGFloat((rgb    & 0x00FF00) >> 8)  / 255.0,
            blue:   CGFloat( rgb    & 0x0000FF)        / 255.0,
            alpha:  CGFloat(alpha)

    This method function creates a new inverted UIColor object of its currently assigned color.

    :returns: UIColor Returns a new UIColor object with the inverted color
    func invert() -> UIColor {
        var red         :   CGFloat  =   255.0
        var green       :   CGFloat  =   255.0
        var blue        :   CGFloat  =   255.0
        var alpha       :   CGFloat  =   1.0

        self.getRed(&red, green: &green, blue: &blue, alpha: &alpha)

        red     =   255.0 - (red * 255.0)
        green   =   255.0 - (green * 255.0)
        blue    =   255.0 - (blue * 255.0)

        return UIColor(red: red / 255.0, green: green / 255.0, blue: blue / 255.0, alpha: alpha)

An Example:

// create our testing view
// with a basic gray background
// as a start
let testingRectView :   UIView  =   UIView(frame: CGRectMake(0,0,50,50))
testingRectView.backgroundColor =   UIColor.grayColor()

// create a new UIColor with a hex color code #990000 (red)
let redColor        :   UIColor =   UIColor(rgb: 0x990000, alpha: 1.0)

// set new background of our testing view
testingRectView.backgroundColor =   redColor

// assign new background color using the invert function on our 
// newly created red color. (output will be #66FFFF)
testingRectView.backgroundColor =   redColor.invert()

Playground Result Image

Dismiss Modal Segue

It's quite strange, but when prototyping an app using storyboard you might already have noticed that there is no segue to dismiss a modal view, which is quite weird as you can push a modal view using a segue, just not the other way around. With this in mind, I made a very very basic DismissModalSegue which allows to dismiss a modal view using only the storyboard. It doesn't matter where connect the segue, as it only needs the source controller and not the destination controller. But I personally like to connect it with the correct destination controller, this makes it visually easier to follow.

IMPORTANT: If the app crashed with the following error: 'Could not find a segue class named 'DismissSegue'' -> Click on the segue in your storyboard. Head over to the attributes inspector inside your utilities toolbar on the right side and check if "Segue module" is not empty. XCode seems to fuck things up on this side. If its empty, just select the first entry in the list. Done, will work now ^^


The class:

class DismissSegue: UIStoryboardSegue {
    override func perform() -> Void {
        let sourceViewController        :   UIViewController  =   self.sourceViewController as UIViewController
        sourceViewController.presentingViewController!.dismissViewControllerAnimated(true, completion: nil)

An Example:

1) Connect push modal segue

Storyboard push modal view

2) Connect the dismiss modal segue

Playground Result Image

3) Test it!

That's it, the views should slide in/out when clicking on the specific button. You can now dismiss modal views with a simple dismiss segue and no coding. You can use prepareForSegue etc. just as on every other segue. Just beware, destinationViewController is not used in this basic example. But you can, of course, enhance it as you wish :D

Say Thanks