简体   繁体   中英

Create custom button with Swift by extending the UIButton class

I'm in the process of learning Swift and I have a basic question. I don't want to use a Storyboard and I want to create a button with code. At the moment, I code my button this way:

let button1: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
button1.setImage(UIImage(named: "myImage.png"), forState: UIControlState.Normal)
button1.addTarget(self, action: "myMethod", forControlEvents: UIControlEvents.TouchUpInside)
button1.frame = CGRectMake(0, 0, 25, 25) // then I add this button to a navigation control

This works, but I'm looking for something slightly different. That is: I want to create a class, I want to pass at least the image name, the method the button must call and the frame. Moreover, I want to instantiate the button in my ViewController whenever I want.

I found many posts here but no post was really useful (some code did not work).

Can you help me?

enum SPBarButtonTypes {
    case openDrawer
    case loginInfo
}

class SPBarButtonFactory: NSObject {

    class func createBarButtonItemOfType (buttonType: SPBarButtonTypes, withTarget buttonTarget: AnyObject, andAction buttonAction: Selector) -> UIBarButtonItem {
        var returnButton: UIBarButtonItem = UIBarButtonItem()
        returnButton.target = buttonTarget
        returnButton.action = buttonAction

        switch buttonType {
            case .openDrawer:
                returnButton.image = UIImage(named: "ic_menu")
            case .loginInfo:
                returnButton.image = UIImage(named: "ic_info_outline")
        default: NSLog("Wrong BarButton type")
        }

        return returnButton
    }

}

ADDED TO IMPROVE COMMENT

It just "seams" like a class nested in another class, but it really is Swifts way to declare a class-method....

This line declares a class named SPBarButtonFactory

class SPBarButtonFactory...

This line declares a class-method of SPBarButtonFactory

class func createBarButtonItemOfType...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM