swift - 将选定行的索引传递给另一个 ViewController

标签 swift xcode indexpath

我有一个关于将索引 (myIndex) 从 TableView 传递到另一个 ViewController 的问题。 我已经发布了下面的代码。好消息:当我运行代码时,索引会传递给另一个 View Controller 。坏消息:这不是我预期的指数。 (当我使用 TableView 在 Viewcontroller 中打印出 myindex 时,一切正常。如果我将 myIndex 传递给另一个 ViewController,则索引会混合在一起......

目标:我的 TableView 由 18 行组成(每个孔一行)。当我单击一行时,将打开另一个 View Controller 。在此 VieController 中,所选行的名称应显示在顶部。 我的想法是将每行的索引传递给另一个 View Controller ,但这无法正常工作。

有人可以帮我吗?

import UIKit
var holes = ["Hole 1","Hole 2","Hole 3","Hole 4","Hole 5","Hole 6","Hole 7","Hole 8", "Hole 9","Hole 10","Hole 11","Hole 12","Hole 13","Hole 14","Hole 15","Hole 16","Hole 17","Hole 18"]
var myIndex = 0

class OverViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    // Label
    @IBOutlet weak var BackButton: UIButton!
    @IBOutlet weak var ScoreButton: UIButton!
    @IBOutlet weak var OverviewLabel: UILabel!
    

    @IBOutlet weak var tableView: UITableView!
    

    override func viewDidLoad() {
           super.viewDidLoad()
    }
    
    
    @IBAction func BackToStartScreen(_ sender: UIButton) {
        performSegue(withIdentifier: "BackToStart", sender: self)
    }
    
    @IBAction func GoToResultScreen(_ sender: UIButton) {
        performSegue(withIdentifier: "GoToResult", sender: self)
    }
    
        
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return holes.count
    }
        
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
            cell.textLabel?.text = holes[indexPath.row]
            return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        myIndex = indexPath.row
        performSegue(withIdentifier: "GoToScore", sender: self)
        
    }
  
}

和 ScoreViewController:

import UIKit



class ScoreViewController: UIViewController {
    var score = 0
    var fairwayhits = 0
    var greeninregulation = 0
    var putts = 0
    var text = ""
        
    // Variable Deklaration
    var CurrentScore = 0
    var CurrentFairwayHits = 0
    var CurrentGreenInRegulations = 0
    var CurrentPutts = 0

    
    
    // Bar Label
    @IBOutlet weak var BackLabel: UIButton!
    @IBOutlet weak var TitleLabel: UILabel!
    
    // Score Elements
    @IBOutlet var ScoreLabel: UILabel!
    @IBOutlet var ScoreStepper: UIStepper!
    @IBOutlet var ScoreResultLabel: UILabel!
    @IBOutlet var ScoreFrameLabel: UILabel!
    
    // Fairway Elements
    @IBOutlet var FairwayLabel: UILabel!
    @IBOutlet var FairwaySwitch: UISwitch!
    @IBOutlet var FairwayResultLabel: UILabel!
    @IBOutlet var FairwayFrameLabel: UILabel!
    
    // Green Elements
    @IBOutlet var GreenLabel: UILabel!
    @IBOutlet var GreenSwitch: UISwitch!
    @IBOutlet var GreenResultLabel: UILabel!
    @IBOutlet var GreenFrameLabel: UILabel!
    
    // Putt Elements
    @IBOutlet var PuttLabel: UILabel!
    @IBOutlet var PuttStepper: UIStepper!
    @IBOutlet var PuttResultLabel: UILabel!
    @IBOutlet var PuttFrameLabel: UILabel!
    
    // Save Button
    @IBOutlet var SaveButton: UIButton!
    
    // Back Button
    @IBAction func BackButtonPressed(_ sender: UIButton) {
        performSegue(withIdentifier: "BackToOverview", sender: self)
    }
    
    // Score Stepper
    @IBAction func ScoreStepperPressed(_ sender: UIStepper) {
        ScoreResultLabel.text = Int(sender.value).description
    }
    
    // Fairway Switch
    @IBAction func FairwaySwitchPressed(_ sender: UISwitch) {
        if FairwaySwitch.isOn {
            CurrentFairwayHits = 1
            FairwayResultLabel.text = "X"
        } else {
            CurrentFairwayHits = 0
            FairwayResultLabel.text = "-"
        }
    }
    
    // Green Switch
    @IBAction func GreenSwitchPressed(_ sender: UISwitch) {
        if GreenSwitch.isOn {
            CurrentGreenInRegulations = 1
            GreenResultLabel.text = "X"
        } else {
            CurrentGreenInRegulations = 0
            GreenResultLabel.text = "-"
        }
    }
    

    // Putt Stepper
    @IBAction func PuttStepperPressed(_ sender: UIStepper) {
        PuttResultLabel.text = Int(sender.value).description
    }
    
    
    // Save Button
    @IBAction func SaveButtonPressed(_ sender: UIButton) {
        if Int(PuttResultLabel.text!)! >= Int(ScoreResultLabel.text!)! {
            showAlert()
        } else {
        score = score + Int(ScoreResultLabel.text!)!
        fairwayhits = fairwayhits + CurrentFairwayHits
        greeninregulation = greeninregulation + CurrentGreenInRegulations
        putts = putts + Int(PuttResultLabel.text!)!
        
        print(score)
        print(fairwayhits)
        print(greeninregulation)
        print(putts)
            
        performSegue(withIdentifier: "ShowResult", sender: self)
        }
    }
    
    
    func showAlert() {
        let alert = UIAlertController(title: "Ops, something went wrong", message: "The number of putts must be smaller than your score!", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: { action in print("tapped Dismissed")}))
        
        present(alert, animated: true)
    }

    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if SaveButton.isTouchInside,
           let resultVC = segue.destination as? ResultViewController
            {

            CurrentScore = score /// get the current cell's text
            CurrentPutts = putts
            resultVC.score = resultVC.score + String((resultVC.ScoreResultLabel.text!))
            resultVC.fairway = String(fairwayhits)
            resultVC.green = String(greeninregulation)
            resultVC.putt = String(putts)
            
            
               }
    }
    
    

    override func viewDidLoad() {
        
        super.viewDidLoad()

        ScoreStepper.wraps = true
        ScoreStepper.autorepeat = true
        ScoreStepper.minimumValue = 1
        ScoreStepper.maximumValue = 20
        
        PuttStepper.wraps = true
        PuttStepper.autorepeat = true
        PuttStepper.minimumValue = 0
        PuttStepper.maximumValue = 20
        

        TitleLabel.text = text
    
    }
}

结果 View Controller :



class ResultViewController: UIViewController {
    
    var score = ""
    var fairway = ""
    var green = ""
    var putt = ""
    

    @IBOutlet weak var TitleLabel: UILabel!
    @IBOutlet weak var BackButton: UIButton!
    @IBOutlet weak var ShareButton: UIButton!
    
    // Score Label
    @IBOutlet weak var ScoreLabel: UILabel!
    @IBOutlet weak var ScoreResultLabel: UILabel!
    @IBOutlet weak var ScoreFrameLabel: UILabel!
    
    // Fairway Label
    @IBOutlet weak var FairwayLabel: UILabel!
    @IBOutlet weak var FairwayResultLabel: UILabel!
    @IBOutlet weak var FairwayFrameLabel: UILabel!
    
    // Green Label
    @IBOutlet weak var GreenLabel: UILabel!
    @IBOutlet weak var GreenResultLabel: UILabel!
    @IBOutlet weak var GreenFrameLabel: UILabel!
    
    // Putt Label
    @IBOutlet weak var PuttLabel: UILabel!
    @IBOutlet weak var PuttResultLabel: UILabel!
    @IBOutlet weak var PuttFrameLabel: UILabel!
    
    // Back Button Action
    @IBAction func BackButtonPressed(_ sender: UIButton) {
        performSegue(withIdentifier: "BackToOverview", sender: self)
        
    }


        
    override func viewDidLoad() {
        super.viewDidLoad()

        ScoreResultLabel.text = "\(score)"
        FairwayResultLabel.text = "\(fairway)"
        GreenResultLabel.text  = "\(green)"
        PuttResultLabel.text = "\(putt)"
        
        
    }
    

 

}

最佳答案

第一件事:你不想在类之外有变量。当然,您可以从所有类(class)访问它们。但是,这不是一个好的做法,您会遇到状态错误。

所以,替换

var holes = ["Hole 1","Hole 2","Hole 3","Hole 4","Hole 5","Hole 6","Hole 7","Hole 8", "Hole 9","Hole 10","Hole 11","Hole 12","Hole 13","Hole 14","Hole 15","Hole 16","Hole 17","Hole 18"]
var myIndex = 0

class OverViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

class OverViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    var holes = ["Hole 1","Hole 2","Hole 3","Hole 4","Hole 5","Hole 6","Hole 7","Hole 8", "Hole 9","Hole 10","Hole 11","Hole 12","Hole 13","Hole 14","Hole 15","Hole 16","Hole 17","Hole 18"]
    var myIndex = 0

并且还替换

var score = 0
var fairwayhits = 0
var greeninregulation = 0
var putts = 0

var text = ""

class ScoreViewController: UIViewController {

class ScoreViewController: UIViewController {
    var score = 0
    var fairwayhits = 0
    var greeninregulation = 0
    var putts = 0

    var text = ""

现在,我假设您想要这种行为:

  1. 按表格 View 上的单元格
  2. 呈现显示单元格文本的 ScoreViewController

您可以将其放入您的 prepareForSegue 函数中:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    guard let selectedPath = tableView.indexPathForSelectedRow else { return }
    if 
        segue.identifier == "GoToScore",
        let scoreVC = segue.destination as? ScoreViewController
    {
        let currentText = holes[selectedPath.row] /// get the current cell's text
        scoreVC.text = currentText
    }
}

编辑:然后,您可以将 TitleLabel.text 设置为 viewDidLoad 内的 text 属性,如下所示:

class ScoreViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        TitleLabel.text = text /// right here!
    }   
}

您还应该将所有属性(包括 TitleLabel 等 socket )保留为小写。这只是一种约定,可以让其他人更轻松地阅读您的代码。

@IBOutlet weak var backLabel: UIButton!
@IBOutlet weak var titleLabel: UILabel!

请记住,要更改 socket 的名称,您需要断开链接并从 Storyboard 重新链接它。

关于swift - 将选定行的索引传递给另一个 ViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66054268/

相关文章:

ios - 如何让 ParseUI 演示在新项目上运行?

ios - ARSessionConfiguration.WorldAlignment = .gravityAndHeading 不稳定的世界原点/对齐

swift - 停止 UIButton 淡出 - Swift

ios - 同一设备 GCM 中的多个通知

ios - Swift iOS - 如何将直接从 TableViewCell 的子类中获取的值传递给 TableView 的 didSelectRow?

swift - 获取节点最后位置

ios - 我刚刚升级到 xcode 到 4.5,现在无法安装 iOS5.1

Swift:将 IndexSet 转换为 [IndexPath]

swift - 在 UICollectionView 中的第二个索引项处启动图像数组

iphone - 触摸移动时拖动图像变慢