我如何从不同的ViewController
问题描述:
访问的tableview自定义单元格都的ViewController Ç其定制的tableView细胞和细胞背景色为蓝色。当我点击从Viewcontroller注销按钮G,我想要Viewcontroller C tableView单元格背景颜色应改为红色。我如何从不同的ViewController
如何访问Viewcontroller C cell in Viewcontroller G?
protocol ChangeCellColor {
func change()
}
import UIKit
class ViewControllerG : UIViewController {
var delegate : ChangeCellColor?
@IBAction func logout_click(_ sender: Any) {
delegate?.change()
}
}
import UIKit
class ViewControllerC : UIViewController {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
cell.contentView.backgroundColor = .red
}
}
extension ViewControllerC : ChangeCellColor {
func change() {
cellColor = UIColor(red: 0.74, green: 0.74 , blue: 0.75 , alpha: 1.0)
tableView.reloadData()
}
}
答
您可以使用Protocol &代表实现您的目标。请按照以下步骤进行:PS:这是未经测试的版本---
编辑:既然你说,有这些viewControllers之间5 VC,所以检查我的编辑答案...
protocol ChangeCellColor {
func change()
}
class ViewControllerG : UIViewController {
var delegate : ChangeCellColor?
@IBAction func btnActionLogout(_ sender: Any) {
delegate?.change()
}
}
class ViewControllerC : UIViewController {
var cellColor : UIColor = .blue
@IBOutlet var tableView : UITableView!
override func viewDidLoad() {
super.viewDidLoad()
let vcG = ViewControllerG() // Or instantiate with SB
vcG.delegate = self // Now maintain this object and eventually at the time of need you have to push the above object in the stack...
}
}
extension ViewControllerC : ChangeCellColor {
func change() {
cellColor = .red
tableView.reloadData()
}
}
extension ViewControllerC : UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "") as? LocationCell else {return UITableViewCell() }
cell.contentView.backgroundColor = cellColor
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
}
尝试解释如何viewControllerC链接到viewControllerG,所以我们可以最好地帮助你回答这个问题。根据链接的类型,答案可能会有所不同。例如viewControllerC呈现viewControllerG。或者viewControllerC将viewControllerG推送到导航堆栈。或者没有链接? – torinpitchers
用于更改Cell背景颜色,您需要使用自定义代理 –
在ViewControllerC和G之间还有另外五个视图控制器,它们通过segue连接。 – SwiftUser