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)
}
}
}
单元格中填充了正确的数据但是当我单击模拟器中的单元格时,它不会移动到相应的视图控制器上面是代码。另外,我如何将单元格内填充的特定数据(如文本和图像资源)移动到相应的视图控制器(我应该将其添加到特定视图的每个相应的swift文件中,还是更容易)?
答案 0 :(得分:0)
首先,您需要确保将ViewController设置为tableView的委托。 其次,从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”的属性。