简体   繁体   English

从代码和情节提要中实例化自定义按钮-如何创建init方法

[英]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? 我将如何创建一个既可以从代码又可以从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. 该错误消息告诉您它正在寻找该coder参数,因为您只有一个init函数。 You haven't declared an initializer with no parameters, so you can't init like: EKLikeButton() 您尚未声明不带参数的初始化程序,因此无法像这样进行初始化: EKLikeButton()

To add an init that accepts a frame parameter, you need to also implement: 要添加一个接受frame参数的init,您还需要实现:

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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