按下按钮后如何更新值?

时间:2017-08-15 07:17:38

标签: swift xcode uitableview tableview

我有两个视图控制器,都有表视图。

根据您在第一个表视图中选择的行,第二个表视图单元格将填充您在初始表视图中选择的最小类别的子类别。在第二个表视图中,还有一个按钮。

我正在尝试将第一个表视图中所选行的值传递给第二个表视图的表视图单元格中的按钮,以便将来使用它并跟踪在第一张表格。

实施此操作的最佳方法是什么?

每次单击第二个表视图I print(initialRow)的表格视图单元格中的按钮,但它始终为0,如何更改它,以便显示正确的值,即所选行的索引第一个表视图?

这是我的第一个表视图的代码:

import UIKit

var trainingDict = ["Ball Handling" : ["1 Ball Stationary Drills", "1 Ball Combo Moves", "2 Ball Stationary Drills", "2 Ball Combo Moves", "2 Ball Partner Drills", "Handle Hoop Drills", "Placeholder"], "Shooting" : ["Form Shooting", "Spot Shooting", "Off The Dribble Shots", "Pull Up Jumpshots", "Catch & Shoots", "Free Throws", "Partner Shooting"], "Defense" : ["5 Star Drill", "Full Court Def. Slides", "1 v 1 Closeouts", "Gauntlet Drill", "Tennis Ball Reaction Drill", "Lane Slides", "Place Holder"], "Advanced Drills" : ["D Man Series", "Iso Series", "Double Move Series", "Gauntlet Series", "John Wall Drill", "Floater Series", "PlaceHolder"], "Vertimax Drills" : ["One Foot Jumps", "Box Jumps", "Resitance Slides", "Resistance Jumps", "Resistance Ball Handling", "Vertimax Sprints", "Slam Drill"], "Full Workouts" : ["Workout A", "Workout B", "Workout C", "Workout D", "Workout E", "Workout F", "Workout G"], "BHB Products" : ["Handle Hoops", "Handle Cubes", "Strech Bands", "Advocare", "Placeholder", "Placeholder2", "Placeholder3"]]

//gradient creation
var gradient : CAGradientLayer!
var drillLabelGradient : CAGradientLayer!
var myIndex = 0


class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: TableView!

    var trainingCategories = [String]()
    var arrayForKey = Array(trainingDict.values)
    var selectedKey = 0
    var rowIcon = [#imageLiteral(resourceName: "bballIcon"), #imageLiteral(resourceName: "pullup"), #imageLiteral(resourceName: "kidBB"), #imageLiteral(resourceName: "girlBB"), #imageLiteral(resourceName: "3ball"), #imageLiteral(resourceName: "dstance"), #imageLiteral(resourceName: "dunk")]

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

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "bell") as! ViewControllerTableViewCell

        //cell details
        cell.backgroundColor = UIColor.clear

        //gradient details
        gradient = CAGradientLayer()
        gradient.frame = tableView.bounds
        gradient.colors = [UIColor.black.cgColor, UIColor.darkGray.cgColor, UIColor.black.cgColor]
        tableView.layer.insertSublayer(gradient, at: 0)
        gradient.startPoint = CGPoint(x: 0.0, y: 0.0)
        gradient.endPoint = CGPoint(x: 1.0, y: 1.0)

        //details what the text label of cell displays
        var trainingCategories = Array(trainingDict.keys)

        myIndex = indexPath.row

        cell.textLabel?.font = UIFont(name: "Symbol", size: 24.0)
        cell.textLabel?.text = trainingCategories[myIndex]
        cell.textLabel?.textColor = UIColor.white
        cell.borderColor = UIColor.white
        cell.borderWidth = 1.5
        cell.imageView?.image = rowIcon[myIndex]

        print(trainingCategories.count)

        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print(indexPath.row)
        selectedKey = indexPath.row
        performSegue(withIdentifier: "segue", sender: self)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "segue" {
            if let secondTableView = segue.destination as? DrillsViewController {
                //how labels in second table view corresspond to the first table view labels
                secondTableView.keyIndex = selectedKey
                secondTableView.arrayForKey2 = arrayForKey
                secondTableView.initialRow = selectedKey
            }
        }
    }     

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
        trainingCategories = Array(trainingDict.keys)
    }
}

第二个表格视图的代码:

import UIKit
import AVKit
import AVFoundation

class DrillsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var initialRow = Int()
    var arrayForKey2 = [[String]]()
    var keyIndex = Int()
    var headLabel = String()
    var labels = Array(trainingDict.keys)

    @IBOutlet weak var tableView: DrillsTableView!

    @IBOutlet weak var drillLabel: UILabel!

    @IBOutlet weak var labelBackground: UIView!

    @IBAction func back(_ sender: Any) {
        performSegue(withIdentifier: "back", sender: self)
    }

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

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! DrillsTableViewCell
        cell.playButton.tag = indexPath.row

        //clear background color needed in order to display gradient cell
        cell.backgroundColor = UIColor.clear



        //details for cell label display
        cell.borderWidth = 1.5
        cell.borderColor = UIColor.white
        cell.drillTitle.text = "\(arrayForKey2[keyIndex][indexPath.row])"
        cell.drillTitle.font = UIFont(name: "Symbol", size: 18.0)
        cell.drillTitle.textColor = UIColor.white

        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! DrillsTableViewCell
        cell.initialRow = initialRow
        print(cell.initialRow)
        print(indexPath.row)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
        drillLabel.text = labels[keyIndex]
    }
}

第二个表视图的表视图单元格的代码:

import UIKit
import AVFoundation
import AVKit

class VideoPlayerView: UIView {

    let pauseButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(#imageLiteral(resourceName: "Triangle 2"), for: .normal)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.tintColor = UIColor.white
        button.isHidden = false
        button.addTarget(self, action: #selector(handlePause), for: .touchUpInside)

        return button
    }()

    var isPlaying = false

    func handlePause() {
        if isPlaying {
            player?.pause()
            pauseButton.alpha = 1.0
        } else { 
            player?.play()
            pauseButton.alpha = 0.01
        }

        isPlaying = !isPlaying
    }

    //container view that holds sublayers for the video control objects
    let controlsContainerView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(white: 0, alpha: 1.0)
        return view
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)

        //configures container view (video's background)
        controlsContainerView.frame = frame
        addSubview(controlsContainerView)
        backgroundColor = UIColor.black

        //following adds pause/play button to video
        controlsContainerView.addSubview(pauseButton)
        pauseButton.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
        pauseButton.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true    
    }

    var player: AVPlayer?

    //function that sets up video playback
    func setupPlayerView(for url: URL) {
        player = AVPlayer(url: url)

        //video only renders if you specify 'playerLayer'
        let playerLayer = AVPlayerLayer(player: player)
        self.layer.insertSublayer(playerLayer, at: 1)
        playerLayer.frame = frame

        player?.play()

        //attached obeserver of 'player' to tell when 'player' is ready
        player?.addObserver(self, forKeyPath: "currentItem.loadedTimeRanges", options: .new, context: nil)
    }

    //method called every time you add obserever to an object
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        //strring that lets AVPlayer know its ready
        if keyPath == "currentItem.loadedTimeRanges" {        
            //configures container view while video is playing
            controlsContainerView.backgroundColor = UIColor.clear
            pauseButton.alpha = 0.03
            isPlaying = true        
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }    
}


class DrillsTableViewCell: UITableViewCell {

    var videoURL:[URL] = [URL(fileURLWithPath: "/Users/jordanlagrone/Desktop/BlackHeartBB/BlackHeartBB/dunk.mov"), URL(fileURLWithPath: "/Users/jordanlagrone/Desktop/BlackHeartBB/BlackHeartBB/mk.MOV")]
    var video = URL(fileURLWithPath: String())
    var initialRow = Int()

    var player: AVPlayer?
    var playerController = AVPlayerViewController()

    @IBOutlet weak var drillTitle: UILabel!

    @IBOutlet weak var playButton: UIButton!
    @IBAction func watchButton(_ sender: UIButton) {
        print(initialRow)
        print(String(sender.tag))

        //controls video background view
        if let keyWindow = UIApplication.shared.keyWindow {
            let view = UIView(frame: keyWindow.frame)
            view.backgroundColor = UIColor.white
            let singleVideoURL = videoURL[sender.tag]

            view.frame = CGRect(x: 0.0, y: 0.0, width: keyWindow.frame.width, height: keyWindow.frame.height)

            let videoPlayerFrame = CGRect(x: 0, y: 0, width: keyWindow.frame.width, height: keyWindow.frame.width * 9 / 16)
            let videoPlayerView = VideoPlayerView(frame: videoPlayerFrame)
            videoPlayerView.setupPlayerView(for: singleVideoURL)
            view.addSubview(videoPlayerView)

            keyWindow.addSubview(view)
            UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut, animations: {
                view.frame = keyWindow.frame
            }, completion: { (completedAnimation) in
                // possible features implemented later
                UIApplication.shared.isStatusBarHidden = true
            })            
        }
    }
}

1 个答案:

答案 0 :(得分:0)

cellForRow中的DrillsViewController方法中,您将单元格显示为DrillsTableViewCell,但从未设置initialRow DrillsTableViewCell属性。这意味着当单元格出列时,initialRow中唯一设置DrillsTableViewCell值的行是

var initialRow = Int()

您需要做的是在initialRow方法

中将DrillsViewController的值initialRowDrillsTableViewCell分配给cellForRow

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! DrillsTableViewCell
    cell.playButton.tag = indexPath.row

    //clear background color needed in order to display gradient cell
    cell.backgroundColor = UIColor.clear

    cell.initialRow = initialRow //THIS IS THE LINE YOU ARE MISSING

    //details for cell label display
    cell.borderWidth = 1.5
    cell.borderColor = UIColor.white
    cell.drillTitle.text = "\(arrayForKey2[keyIndex][indexPath.row])"
    cell.drillTitle.font = UIFont(name: "Symbol", size: 18.0)
    cell.drillTitle.textColor = UIColor.white

    return cell
}