[英]iOS Swift: Pushing a View Onto the Stack From Within a Custom Tableview Cell
我在具有导航控制器的VC内有一个tableview,它包含自定义表格单元格。 我想知道如果点击自定义表格单元格中的按钮,将最佳方法推入父VC的导航堆栈的最佳做法。 如果我将父VC的导航控制器传递到该单元格,则可以使它正常工作; 但这是最有效的方法吗? 请在下面查看我当前的实现:
UserAccountVC:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:TextPostTableViewCell = Bundle.main.loadNibNamed("TextPostTableViewCell", owner: self, options: nil)?.first as! TextPostTableViewCell
cell.setupCell(navigationController: self.navigationController!)
cell.selectionStyle = .none
return cell
}
CustomTableCell:
import UIKit
class TextPostTableViewCell: UITableViewCell {
var aNavigationController: UINavigationController!
//MARK: Actions
@IBAction func profilePicButtonTapped() { //We want to present a users profile
let sb = UIStoryboard(name: "SuccessfulLogin", bundle: nil)
let cc = (sb.instantiateViewController(withIdentifier: "otherUserViewController")) as! OtherUserAccountViewController
self.aNavigationController.pushViewController(cc, animated: true)
}
func setupCell(navigationController: UINavigationController) -> Void {
aNavigationController = navigationController
}
}
先感谢您!
不,这不是最佳做法。 您可以在界面构建器中为UIButton
设置IBAction
或将UIViewController
添加为cellForRowAt
的目标。 无论使用哪种方法,您都可能需要一些标识indexPath的方法,因为您没有在tableview委托中使用didSelectRow
:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:TextPostTableViewCell = Bundle.main.loadNibNamed("TextPostTableViewCell", owner: self, options: nil)?.first as! TextPostTableViewCell
cell.button.tag = indexPath.row // Or use some other method of identifying your data in `myAction(_:)`
cell.button.addTarget(self, action:, @selector(myAction(_:)), for: .touchUpInside)
...
}
您可以在这种情况下使用委托。
这里的代码更多,但这在iOS开发IMO中是更好的方法。
class ViewController: UIViewController {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:TextPostTableViewCell = Bundle.main.loadNibNamed("TextPostTableViewCell", owner: self, options: nil)?.first as! TextPostTableViewCell
cell.delegate = self
cell.selectionStyle = .none
return cell
}
}
extension ViewController: TextPostTableViewCellDelegate {
func didTappedProfilePicButton() {
let sb = UIStoryboard(name: "SuccessfulLogin", bundle: nil)
let cc = (sb.instantiateViewController(withIdentifier: "otherUserViewController")) as! OtherUserAccountViewController
navigationController?.pushViewController(cc, animated: true)
}
}
protocol TextPostTableViewCellDelegate: class {
func didTappedProfilePicButton()
}
class TextPostTableViewCell: UITableViewCell {
weak var delegate: TextPostTableViewCellDelegate?
//MARK: Actions
@IBAction func profilePicButtonTapped() { //We want to present a users profile
delegate?.didTappedProfilePicButton()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.