简体   繁体   中英

Instantiate custom button from code and Storyboard - how to make an init method

I would like to create a button like this:

import UIKit

class EKLikeButton: UIButton {

  required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.layer.cornerRadius = 5.0;
    self.layer.borderColor = UIColor.redColor().CGColor
    self.layer.borderWidth = 1.5
    self.backgroundColor = UIColor.blueColor()
    self.tintColor = UIColor.whiteColor()

  }
}

but the only way to make it seems to be to set a pre-existing button in a Storyboard. I'd like to be able to do:

let btn = EKLikeButton()
btn.frame=CGRectMake(10.0, 10.0, 40.0, 40.0)

but when I try the above, I get

Missing argument for parameter 'coder' in call

How would I make an init function that can handle both from code or from storyboard in Swift?

This is what I usually do

class EKLikeButton: UIButton {

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

    }
    init(){
        super.init(frame: CGRectZero)
        setUp()
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUp()
    }
    func setUp(){
        self.layer.cornerRadius = 5.0;
        self.layer.borderColor = UIColor.redColor().CGColor
        self.layer.borderWidth = 1.5
        self.backgroundColor = UIColor.blueColor()
        self.tintColor = UIColor.whiteColor()
    }
}

That error message is telling you that it's looking for that coder param, because you only have that one init function. You haven't declared an initializer with no parameters, so you can't init like: EKLikeButton()

To add an init that accepts a frame parameter, you need to also implement:

override init(frame: CGRect) {
    super.init(frame: frame)
    // set up your frame, init, whatever
}

Then you can instantiate it like this:

let btn = EKLikeButton(CGRect(10, 10, 40, 40))

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