【问题标题】:setting initializer (init) in a subclass swift在子类中快速设置初始化程序(init)
【发布时间】:2017-10-26 15:23:34
【问题描述】:

我试图了解如何从另一个类调用,例如 let creation = menuButtonController(image:#imageLiteral(resourceName: "maps")) 然后在 menuButtonController我设置这个:

class menuButtonController: UIView {

    let buttonView = UIView()
    let button = UIButton(type: .custom)
    var imageButton: UIImageView


    init(frame: CGRect, image: UIImage) {
        super.init(frame: frame,image: image) //Cannot invoke  UIView.init with an argument list of type (frame cgrect, image uiimage)
        self.imageButton.image = image
    }

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

它给了我一个我无法解决的错误。谁能帮帮我?

编辑

现在如果我只想用(image: UIImage) 调用初始化程序,我应该像这样使用convenience init 吗?

convenience init(image: UIImage) {
    self.init(image: image)
    self.imageButton.image = image
}

当我尝试运行应用程序时它不会给我错误但会崩溃

【问题讨论】:

  • 你能分享你得到的错误是什么吗?
  • 我把它写在代码里面的注释里。这是一个副本:不能使用类型参数列表调用 UIView.init (frame cgrect, image uiimage)
  • xxxController 形式的名称命名UIView 的子类是一个糟糕的想法。视图对象和控制器对象是完全不同的动物,名为xxxController 的对象应该是控制器对象,而不是视图对象。哦,类名应该以大写字母开头。所以你的班级应该命名为MenuButtonView

标签: ios swift init initializer


【解决方案1】:

超类UIView中没有方法init(frame: CGRect, image: UIImage)。需要先初始化imageButton,然后调用指定的初始化器init(frame

init(frame: CGRect, image: UIImage) {
    self.imageButton.image = image
    super.init(frame: frame)
}

顺便说一句:类名应该以大写字母开头。

【讨论】:

  • ...并且视图对象的名称不应以“Controller”结尾...
  • 现在它向我显示一个错误:属性 self.imagebutton 在 super.init 调用时不是初始化程序(在 Menubutton 中更改了类
  • 是的,我写了你需要先初始化imageButton
  • 好的,谢谢,我还有一个问题。如果我只想调用带有图像的初始化程序:UIImage? (见主帖中的编辑)
  • 在任何情况下,您都必须调用超类中的(指定)初始化程序,或者调用超类中适当初始化程序的便利初始化程序。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-20
相关资源
最近更新 更多