how to call presentViewController from within a UICollectionViewCell

后端 未结 2 1594
南方客
南方客 2020-11-29 07:19

calling this function from a UIViewController results in no problems, but calling it from a UICollectionViewCell raises a pre-compilation error

2条回答
  •  醉梦人生
    2020-11-29 07:37

    That's because presentViewController is a UIViewController method, UITableViewCell does not has a method called presentViewController.

    what to do?

    You can use Delegation pattern for handling accessing the of the button's action (as @alexburtnik answer), or -for saving some extra work- I suggest to handle the action of the cell's button in the viewController by recognizing it via tag for it.

    Note: Swift 3 Code.

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! TableViewCell
    
            cell.myButton?.tag = indexPath.row
            cell.myButton?.addTarget(self, action: #selector(), for: .touchUpInside)
    
            return cell
        }
    
        func namesIsTapped(tappedButton: UIButton) {
            // get the user (from users array for example) by using the tag, for example:
            let currentUser = users[tappedButton.tag]
    
            // do whatever you want with this user now...
    
        }
    

    Hope that helped.

提交回复
热议问题