找出swift中单击按钮的父视图

时间:2015-06-19 18:59:37

标签: ios swift

我有一些代码,我有3个按钮,我想在点击时查找这些按钮的父视图

 @IBAction func resizeButtonClicked(sender: UIButton) {
    if(sender.isEqual(resizeButton)) {
        //This is to convert to small square
    } else if(sender.isEqual(maximizeButton)) {
        //This is to convert to maximized view
    } else if(sender.isEqual(closeButton)) {
        //This is to close the view completely

    }
}

现在我可以识别发件人按钮,但如何识别此按钮所在的视图?

谢谢

尼基尔

3 个答案:

答案 0 :(得分:49)

请尝试以下

sender.superview

答案 1 :(得分:2)

我不想创建自定义类,也不想使用accessibilityHin:

    func performAction(_ sender : AnyObject?)
{
    let cell = sender?.superview??.superviewOfClassType(UITableViewCell.self) as! UITableViewCell
    let tbl = cell.superviewOfClassType(UITableView.self) as! UITableView
    let indexPath = tbl.indexPath(for: cell) 
    let myData = myDataArray[indexPath.row]
    ...
}

答案 2 :(得分:0)

如果要在视图层次结构中甚至在父级控制器或任何其他响应者中寻找特定的父级,则可以使用此扩展名:

Collections.sort

用法示例

以下内容返回包含extension UIResponder { func nextFirstResponder(where condition: (UIResponder) -> Bool ) -> UIResponder? { guard let next = next else { return nil } if condition(next) { return next } else { return next.nextFirstResponder(where: condition) } } } 的{​​{1}}。无论它嵌套在视图和子视图中有多深。

tableViewController