ios - 我的协议(protocol)和委托(delegate)不起作用?

标签 ios swift delegates protocols

我创建了一个协议(protocol),通过委托(delegate)将“itemInformation”传递给其他 View Controller ,如下所示:

 protocol ItemDataDelegate {

func ItemInformation(itemID:String,itemname:String,itemPrice:String)
}


class ItemTableViewCell: UITableViewCell {

var passItemID:String?
var PassItemName : String?
var PassAddon : String?
var PassItemPrice : String?

var Itemdelegate: ItemDataDelegate?


@IBOutlet var itemName: UILabel!
@IBOutlet var itemPrice: UILabel!



override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code

}

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state

}


@IBAction func OrderBtnPressed(sender: AnyObject) {


    print(PassItemName)
    print(PassAddon)
    print(passItemID)
    print(PassItemPrice)



        let itemnameInfo:String = PassItemName!
        let itempriceInfo:String = PassItemPrice!
        let itemID:String = passItemID!

        Itemdelegate?.ItemInformation(itemID,itemname:itemnameInfo as String, itemPrice: itempriceInfo as String)




}

}

现在我通过在下面实现它来检索协议(protocol)。例如,我只是想在这里打印传递值,但没有任何反应。

class CustomAddOnVC:   UIViewController,UITableViewDataSource,UITableViewDelegate, ItemDataDelegate{

 var ItemTableViewCellObj:ItemTableViewCell? 

override func viewDidLoad() {
    super.viewDidLoad()

ItemTableViewCellObj?.Itemdelegate = self

}

  func ItemInformation(itemID: String, itemname: String, itemPrice: String) {
    print(itemID)
    print(itemname)
    print(itemPrice)
}

}
我在这里做错了吗?

最佳答案

在 CustomAddOnVC 中请写入

 ItemTableViewCellObj.Itemdelegate = self 

在viewDidLoad或者ItemTableViewCell的地方。在初始化的 .并定义带有弱引用的委托(delegate)

weak var Itemdelegate: ItemDataDelegate?

替换 ItemTableViewCell OrderBtnPressed 方法中的这一行

 Itemdelegate?.ItemInformation(itemID,itemname:itemnameInfo as String, itemPrice: itempriceInfo as String)

有了这个

self.itemDelegate?.itemInformation("itemID", itemname: "itemname", itemPrice: "itemPrice")

关于ios - 我的协议(protocol)和委托(delegate)不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39014727/

相关文章:

ios - 如何从 iOS 中的 firebase 数据库获取最新消息

coldfusion - ColdFusion 是否支持委托(delegate)?

ios - superview 的 inputViewController 在点击 subview(UITextView) 时被调用

c++ - OpenCV c++ 示例到 iOS 项目

ios - OpenCV - 无法访问 Mat 中的所有像素

ios - ftp图片上传导致图片被快速截断

ios - 如何通过自定义字段查找自定义 View

iphone - 在 iOS 中从 NSFileWrapper 播放电影

objective-c - 如何将数据从 TextField/TextView 发送到另一个 View ?

c# - 如何在 C# 中创建完全参数化的方法委托(delegate)?