从UIViewController调用此函数不会造成任何问题,但从UICollectionViewCell调用该函数会引发预编译错误。
函数:
func didTapShare(sender: UIButton)
{
let textToShare = "Swift is awesome! Check out this website about it!"
if let myWebsite = NSURL(string: "http://www.google.com/")
{
let objectsToShare = [textToShare, myWebsite]
let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
activityVC.excludedActivityTypes = [UIActivityTypeAirDrop, UIActivityTypeAddToReadingList]
activityVC.popoverPresentationController?.sourceView = sender
self.presentViewController(activityVC, animated: true, completion: nil)
}
}错误:
您的单元没有成员presentViewController。
该怎么办呢?
发布于 2016-10-18 15:12:11
UITableViewCell不应该处理任何业务逻辑。它应该在视图控制器中实现。您应该使用委托:
UICollectionViewCell子类:
protocol CustomCellDelegate: class {
func sharePressed(cell: MyCell)
}
class CustomCell: UITableViewCell {
var delegate: CustomCellDelegate?
func didTapShare(sender: UIButton) {
delegate?.sharePressed(cell: self)
}
}ViewController:
class TableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
//...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! CustomCell
cell.delegate = self
return cell
}
}
extension TableViewController: CustomCellDelegate {
func sharePressed(cell: CustomCell) {
guard let index = tableView.indexPath(for: cell)?.row else { return }
//fetch the dataSource object using index
}
}发布于 2016-10-18 15:33:38
这是因为presentViewController是一个UIViewController方法,UITableViewCell没有一个名为presentViewController的方法。
该怎么办呢?
您可以使用委派模式来处理按钮操作的访问(作为@alexburtnik应答),或者使用-for来节省一些额外的工作--我建议通过tag对其进行识别,从而在viewController中处理单元格按钮的操作。
注: Swift 3代码。
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...
}希望能帮上忙。
https://stackoverflow.com/questions/40111778
复制相似问题