Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to add custom variables to exising classes like UIButton?

Tags:

ios

swift

In my app, I heavily depend on different view types and they will hold different values. For example, for a button I will need it to have 4 additional variables and I implemented it like this:

import UIKit

class ActionButton: UIButton {

    var row = 0
    var action = 0
    var appDataId = ""
    var companyId = ""

}

And I use a ActionButton instead of UIButton.

However I will need a lot of these for different types of views like labels buttons etc and it might complicate the project.

My question is, is that a good practice? Is there any other way to achieve same result ?

Thanks!

like image 485
Jacob Smith Avatar asked Mar 12 '23 08:03

Jacob Smith


1 Answers

METHOD 0: What you already showed us works fine :D

Thats is: subclassing an existing Class and customising it with your vars. You will just have to copy paste that button or set the class of newly created buttons to ActionButton.

But there are more interesting solutions in my opinion.


METHOD 1: Create a UIButton extension and use Associated Objects in place of stored vars.

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Extensions.html

There is also an alternate way:

Extensions May not contain Stored properties


METHOD 1.5 (RECOMMENDED SOLUTION):

Make an extension of UIView. UILabel and UIButton as well as many other UI elements inherit from it. What you put in your UIView extension will be accessible to all classes that inherit from UIView.


BONUS METHOD (if you want or need to go a step further): Create a custom UIButton Class and use IBInspectables !

You will then be able to modify the vars directly from the Interface builder which is very handy for testing !

Example:

//
//  CustomButton.swift


import UIKit

@IBDesignable
class CustomButton: UIButton {

    @IBInspectable var cornerRadius: CGFloat = 3.0 {
        didSet {
            setupView()
        }
    }

    @IBInspectable var fontColor: UIColor = UIColor.whiteColor() {
        didSet {
            self.tintColor = fontColor
        }
    }

    override func awakeFromNib() {
        setupView()
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        setupView()
    }

    func setupView() {
        self.layer.cornerRadius = cornerRadius

    }
like image 142
Coder1000 Avatar answered May 07 '23 01:05

Coder1000