xcode 从用作tableHeaderView的xib文件内的按钮转到VC

sg2wtvxw  于 2022-12-14  发布在  其他
关注(0)|答案(2)|浏览(123)

我有一个TableSectionHeaderxib文件,里面有一个button(和一些其他的东西),这个xib文件在我的PostViewController里面被用作UItableviewcustom header
我希望能够点击该按钮来显示有关单元格的详细信息。但是,由于该按钮位于xib文件内部,因此IBAction位于TableSectionHeader.Swift(从UITableViewHeaderFooterView继承而来)内部。这意味着我不能使用segue or instantiate作为VC。
如何从xib文件中的这个按钮转到另一个VC?

lx0bsm1f

lx0bsm1f1#

您需要将按钮的出口(outlet)放入xib类中,而不是一个操作,当您在视图控制器中创建并返回头文件时,在返回头文件之前,您将获得按钮的引用,然后将addTarget指向按钮,并使用selector标记指向将处理下一个视图控制器的方法。
在您的xib类中拖动并连接按钮:

class YearSectionHeader : UITableViewHeaderFooterView {

@IBOutlet car button :UIButton!

}

在视图控制器表的视图头方法(示例)中,不要忘记将类更改为,并将标识符更改为您使用的正确值:

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        let header : YearSectionHeader = tableView.dequeueReusableHeaderFooterViewWithIdentifier("TableHeader") as! YearSectionHeader
        header.button.addTarget(self, action: #selector(self.handlingMethodName(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        header.button.tag = section
        return header

    }

sender.tag是您的部分编号,您可以在此处执行以下步骤:

func handlingMethodName(sender:UIButton){

        print(sender.tag)

    }
oalqel3c

oalqel3c2#

这里只是借用了Aaoli的答案--这段代码可以工作。我简直不敢相信。您需要将IBAction连接到XIB文件,并且在视图控制器中也有完全相同的IBAction行,但没有连接。
XIB文件(连接到单元,但不添加任何代码:

@IBAction func completePressed(_ sender: UIButton) {
}

视图控制器:

@IBAction func completePressed(_ sender: UIButton) {
    print("holler")
}

现在,在表视图所在的视图控制器中,放入以下代码:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let header : TestCell = itemTableView.dequeueReusableCell(withIdentifier: "testCell") as! TestCell
    header.compLabel.addTarget(self, action: #selector(self.completePressed(_:)), for: UIControl.Event.touchUpInside)
    header.compLabel.tag = section

    return header

}

事实上,这是令人惊讶的工作,我不知道为什么

相关问题