【问题标题】:Property 'self.delegate' not initialised at super.init属性“self.delegate”未在 super.init 初始化
【发布时间】:2016-07-18 12:42:13
【问题描述】:

我正在尝试在 UITableViewCell 类中创建协议,但是当我声明我的委托时,required init?(coder aDecoder: NSCoder)override init(style: UITableViewCellStyle, reuseIdentifier: String?) 都出现错误

错误:-Property 'self.delegate' not initialised at super.init

这是我的子类:-

import UIKit

protocol tableCellBtnActionDelegate{

func removeRowAtIndex(_: Int)

}

class FriendsListTableViewCell: UITableViewCell {
@IBOutlet weak var friendListAddBtn: UIButton!
var usersId : String!
var buttonText : String!
var indexPath : Int!
let delegate : tableCellBtnActionDelegate!
override func awakeFromNib() {
    super.awakeFromNib()
    friendListAddBtn.layer.cornerRadius = 4
    friendListAddBtn.layer.backgroundColor = UIColor(red: 121.0/255.0, green: 220.0/255.0, blue: 1, alpha: 1).CGColor
}

required init?(coder aDecoder: NSCoder) {

    super.init(coder: aDecoder)
}
override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {

    super.init(style: style, reuseIdentifier: reuseIdentifier)

}
}

【问题讨论】:

    标签: ios swift uitableview swift-protocols


    【解决方案1】:

    你还没有初始化它,所以编译器会给你一个警告。 我建议您将委托修改为可选,并在需要时设置您的委托。

    var delegate : tableCellBtnActionDelegate? 
    

    您还应该处理未设置委托(nil)的情况。

    【讨论】:

    • 我这样做了,没有帮助。委托函数没有被调用,当我将它改回var delegate : tableCellBtnActionDelegate!时,它给了我一个错误:'nil'。
    • 这是解决您的问题的正确答案。您需要确保正确设置委托并调用委托方法。您还没有显示这些代码中的任何一个
    【解决方案2】:

    改变

    let delegate : tableCellBtnActionDelegate!
    

    var delegate : tableCellBtnActionDelegate!
    

    或者你永远不能为委托属性设置值

    【讨论】:

    • 可以将值设置为 let + 隐式展开的可选:在 init. OP 就是不这样做。
    • @EricD ty 发表评论,让回答更全面;我只是不相信他想在 init 中设置委托
    【解决方案3】:

    您收到警告,因为您没有初始化 delegate 属性。它实际上应该是一个弱属性,否则您将保留对委托对象which you usually don't want to do 的引用。所以最好的方法是:

    weak var delegate : tableCellBtnActionDelegate?

    然后你必须像这样使用它:

    self.delegate?.notifyAboutSomething()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-06
      • 1970-01-01
      • 2014-10-09
      • 2015-07-05
      • 2021-12-22
      • 1970-01-01
      • 2016-11-08
      • 1970-01-01
      相关资源
      最近更新 更多