Swift popViewController发送数据

时间:2018-07-20 09:57:55

标签: ios swift uinavigationcontroller

class SelectTag: UIViewController {
    var selectedTag = [0,1,2]

    @IBAction func endSelectTag(_ sender: Any) {

        self.navigationController?.popViewController(animated: true)
    }
}

我可以在运行popViewController之前添加数据吗?

我尝试过

(self.parent as! MyPage).seleteTag = seletedTag

Could not cast value of type UINavigationController to MyPage

2 个答案:

答案 0 :(得分:1)

您似乎正在尝试将数据从SelectTag传递到MyPage

一种方法是使用委托模式。

创建一个SelectTagDelegate

protocol SelectTagDelegate : class {
    func didSelectTag(tags: [Int])
}

SelectTag中添加此属性:

weak var delegate: SelectTagDelegate?

然后将endSelectTag更改为:

@IBAction func endSelectTag(_ sender: Any) {
    delegate?.didSelectTag(tags: selectedTag)
    self.navigationController?.popViewController(animated: true)
}

通过实现MyPage使SelectTagDelegate符合didSelectTag

extension MyPage: SelectTagDelegate {
    func didSelectTag(tags: [Int]) {
        seleteTag = tags
    }
}

现在,当您演示SelectTag时,请将self设置为代表。

let selectTag = // get VC from storyboard or use segue.destination depending on your situation
selectTag.delegate = self
// present the VC

答案 1 :(得分:0)

protocol SelectTagDelegate : Nsobject {
func clickedTag(tag: Int)
}

class SelectTag: UIViewController {
var selectedTag = [0,1,2]
var delegate : SelectTagDelegate?
@IBAction func endSelectTag(_ sender: Any) {
     self.delegate.clickedtag(selectedtag)

    self.navigationController?.popViewController(animated: true)
}
}

现在,当您创建SelectTag对象时,将其委托分配给self并实现方法clickedTag。