import Foundation
import UIKit
class ServiceLines: UIViewController{
@IBOutlet weak var servicesTableView: UITableView!
var ServiceA: [Service] = []
var identities = [String]()
override func viewDidLoad(){
super.viewDidLoad()
ServiceA = Services()
identities = ["Service1","Service2","Service3"]
}
func Services() -> [Service]{
var releaseServices: [Service] = []
let Service1 = Service(titled: "Test1", description: "Test", image: #imageLiteral(resourceName: "Test"))
let Service2 = Service(titled: "Test2", description: "Test", image: #imageLiteral(resourceName: "Test"))
let Service3 = Service(titled: "Test3", description: "Test", image: #imageLiteral(resourceName: "Test"))
releaseServices.append(Service1)
releaseServices.append(Service2)
releaseServices.append(Service3)
return releaseServices
}
}
extension ServiceLines: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ServiceA.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let ServiceB = ServiceA[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier:"ServicesTableViewCell") as! ServicesTableViewCell
cell.setServices(service: ServiceB)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
func prepareForSegue(segue: UIStoryboardSegue, sender: Any) {
let vcName = identities[indexPath.row]
let viewController = storyboard?.instantiateViewController(withIdentifier: vcName)
self.navigationController?.pushViewController(viewController!, animated: true)
}
}
}
单元格填充了正确的数据,但是当我单击模拟器中的单元格时,它不会移动到上面相应的 View Controller ,这是代码。另外,如何将单元格内部填充的特定数据(例如文本和图像资源)移动到相应的 View Controller (我应该将其添加到该特定 View 的每个相应的 swift 文件中,还是更简单的方法)?
最佳答案
首先,您需要确保您的 ViewController 被设置为 tableView 的委托(delegate)。 其次,从 didSelectRow 中删除prepareForSegue。
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vcName = identities[indexPath.row]
let viewController = storyboard?.instantiateViewController(withIdentifier: vcName)
// Here you can pass the data you need to the new ViewController
let service = releaseServices[indexPath.row]
viewController?.service = service
// or if you need only the image
viewController?.serviceImage = service.image
self.navigationController?.pushViewController(viewController!, animated: true)
}
我假设您的 viewController 中有一个名为“service”或“image”的属性。
关于swift - 将 tableviewcell 连接到多个 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48612968/