簡體   English   中英

將信息從tableview傳遞給視圖控制器而不是基於indexPathForSelectedRow,而是傳遞給選定單元格的標簽文本?

[英]Pass information from a tableview to a view controller based not on indexPathForSelectedRow, but on label text of cell selected?

我在UIViewController里面有一個tableview ,在Main.storyboard ,我從第一個視圖控制器中tableview上的原型單元到第二個視圖控制器有一個show segue。 我有這個代碼:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showTheSeriesPage"
    {
        let indexPath : NSIndexPath = self.theTableAyy.indexPathForSelectedRow! as NSIndexPath
        var destViewController = segue.destination as! SeriesPageViewController
        var randomTemporaryArray = dataAry[indexPath.row]

        destViewController.sampleTitle = randomTemporaryArray.objectSeriesTitle
        destViewController.sampleAuthor = randomTemporaryArray.objectSeriesAuthor
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}

它可以工作,但只有當tableview按特定順序並且基於indexPath.row ,而不是基於單元本身的特定細節。 如何設置它以使其不依賴於所選的indexPath.row ,但可能是單元格的標簽文本? 謝謝!

簡短的回答:不要這樣做。 您當前的方法是正確的。 您應該有一個包含表視圖中顯示的信息的數據模型。 當用戶點擊一個單元格時,您應該使用所選單元格的indexPath來查找模型中的條目,然后獲取適合該條目的任何字符串。

單元格是視圖對象,您不應使用它們來存儲信息。

我理解這個問題,因為當您將TableView與搜索按鈕鏈接時,這很常見。 特別是,如果您有一個鏈接到表格結果的搜索欄,則會動態更改。

我看了很多使用prepareForSegue函數的帖子,但我想使用prepare函數來切換到你的下一個視圖。 就我而言,擁有一個更受控制的代碼區域,可以從單個包含的函數中發送segue。

我的解決方案:1。我必須在視圖控制器中聲明2個變量來存儲過濾結果(表視圖中的動態新列表)和所選行。 例如,如果我們處理汽車清單,那么,

var filteredCars = [Car]()
var selectedCar: AnyObject!

然后在searchBar函數中:

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

    filteredCars = self.cars.filter({ (x: Car) -> Bool in

        return x.name?.lowercased().range(of: searchText.lowercased()) != nil

    })

    self.tbvOriginalTable.reloadData()
    // IMPORTANT store the new filtered table results to use them later
    saveFilteredTable = self.tbvOriginalTable

}

現在在准備功能:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier == "optionlist" {

        let controller = segue.destination as! MealListTableViewController
        // this is the declared @IBOutlet weak var searchCar: UISearchBar!
        if searchCar.text != "" {
controller.car = filteredCars[(saveFilteredTable.indexPathForSelectedRow?.row)!]

        } else {
            controller.car = cars[(tbvOriginalTable.indexPathForSelectedRow?.row)!]
        }
    }
}
// We have to use the controller to assign an object of type car on the other side of the segue to receive the passed record

這真的為我做了伎倆,它花了我一些閱讀和研究,最后完成它而不需要使用func tableView(_ tableView:UITableView,didSelectRowAt indexPath:IndexPath)加上prepareForSegue函數或任何其他類型的長編碼

我希望這對許多人也有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM