swift - 如何将两个 View Controller 链接到以编程方式创建的 TableView ?

标签 swift storyboard tableview segue

<分区>

抱歉我的英语不好。

我想要这个:当有人点击一个单元格时,它会在另一个 View Controller 中打开。

我以编程方式创建了 TableView 。

import UIKit
class BibleBooksViewController: UIViewController, UITableViewDelegate, 
UITableViewDataSource {

private let myArray: NSArray = ["Gênesis", "Êxodo", "Levitico"]
private var myTableView: UITableView!
var bibleArray = BibleBooksMock().booksArray

override func viewDidLoad() {
    super.viewDidLoad()

    let barHeight: CGFloat =
UIApplication.shared.statusBarFrame.size.height
    let displayWidth: CGFloat = self.view.frame.width
    let displayHeight: CGFloat = self.view.frame.height

    myTableView = UITableView(frame: CGRect(x: 0, y: barHeight, width: 
displayWidth, height: displayHeight - barHeight))
    myTableView.register(UITableViewCell.self, forCellReuseIdentifier: 
"MyCell")
    myTableView.dataSource = self
    myTableView.delegate = self
    self.view.addSubview(myTableView)
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: 
Int) -> Int {
    return bibleArray.count
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: 
IndexPath) -> CGFloat {
    return 70
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) 
-> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: 
indexPath as IndexPath)
    cell.textLabel!.text = "\(bibleArray[indexPath.row].title)"
    return cell
 }
}

输出是这样的:

The code output img from the code

iOS版本为12.1 swift版本是4.2

最佳答案

当我们点击单元格时,在tableview didselect 方法中使用此代码此方法用于操作

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            let vc = self.storyboard?.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
            vc.strText = "\(arrData[indexPath.row])"
            self.present(vc, animated: true, completion: nil)
             OR
            self.navigationController?.pushViewController(vc, animated: true)
        }

当我们必须传递ViewController是DetailViewController的数据或导航时

class DetailViewController: UIViewController {

    var strText: String?

    override func viewDidLoad() {
        super.viewDidLoad()
        yourlabel.text = strText
    }

}

在我的代码中,我使用 DetailViewController 作为 Storyboard ID,因此像在 SS 中一样在 Storyboard 中设置它。

enter image description here 你可以在 youtube 上查看我的视频 :- https://www.youtube.com/watch?v=4MOiU_Qop-0

关于swift - 如何将两个 View Controller 链接到以编程方式创建的 TableView ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53900054/

相关文章:

ios - swift : Subclassing SlackTextViewController in tableview

ios - 在 segue 中使用类时遇到问题

xcode - 使用 contentsOfFile 的 UIImage

ios - 如何知道文件是否已编码?

swift - WatchKit:每当调用自定义 WKInterfaceButton 类上的函数时,都会因 exc_bad_access 失败

c# - 获取 UIControl Xamarin iOS 的名称

ios - 动态静态 TableView

swift - NSImage 不适用于所有图像

ios - 在 TabBarViewController 的选项卡之间传递数据

ios - setSeparatorStyle 仅在 1 个部分