Loc Dai Le
Loc Dai Le

Reputation: 1707

Save styled element to reuse in other view controllers

I'm making an iOS app with Xcode where all my buttons should have the same style. The only difference between these buttons are their height and width. Is there a way to save the first one I styled, and then use it again in the different view controllers, without copying? I'm thinking if this is possible it'll save me a lot of time.

Upvotes: 1

Views: 683

Answers (1)

R Menke
R Menke

Reputation: 8411

Applying the same style to multiple instances of UIButton:


Strictly Programmatic route:

The first two methods are what I would do. The third is only to illustrate that it is possible to write an init that copies settings from another button.

Apply preset style with a sub class:

class StyledButton : UIButton {        

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.blackColor()
        // more styling
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

Apply preset style with an extension to UIButton:

extension UIButton {

    func setCustomStyle1() {

        self.backgroundColor = UIColor.blackColor()
        // nore styling

    }
}

Copy style with a convenience init in an extension to UIButton:

extension UIButton {

    convenience init(styleFromButton button: UIButton, frame: CGRect) {

        self.init(frame: frame)

        self.backgroundColor = button.backgroundColor

    }
}

Interface Builder solution:

Create a new Swift file:

enter image description here enter image description here

Create a sub class of UIButton in the new file:

class StyledButton : UIButton {

    override init(frame: CGRect) {
        super.init(frame: frame)
        style()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        style()
    }

    private func style() {
        self.backgroundColor = UIColor.blackColor()
        // more styling
    }
}

Go back to the Interface Builder and select a UIButton you want to style. Select the third panel on the right, this is the identity inspector. Select your sub class as the class for the UIButton.

Repeat for all buttons to style.

enter image description here


Or style the entire thing in IB and Alt-Drag to make a copy.

Upvotes: 6

Related Questions