如何在UITableView中实现“先进先出”方法?

我实现了一些Swift代码,以在用户滑动屏幕时在tableView中一个接一个地显示单元格标签。

为此,我在words中存储了一个单词列表,而在tableView中只有它的第一项可见。然后,当用户滑动屏幕时,它将使用words中的下一个单词设置下一个单元格的标签。由于words包含一长串单词,因此启用了滚动。

PlayViewController.swift中,我处理UITableView和手势,而在PlayTableViewCell.swift中,我设置UITableViewCell。在ListViewController.swift中,我问用户他/她想在words数组中存储哪些单词。

PlayViewController.swift

class PlayViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    @IBOutlet weak var playTableView: UITableView!

    var words = [String]()

    var numberOfRevealedLabels = 1

    var numberOfGoodAnswers = 0
    var numberOfWrongAnswers = 0

    var indexGA = 0
    var indexWA = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        playTableView.delegate = self
        playTableView.dataSource = self

        self.playTableView.estimatedRowHeight = 50.0

        view.isUserInteractionEnabled = true

        let swipeRight = UISwipeGestureRecognizer(target: self,action: #selector(self.respondToSwipeGesture))
        swipeRight.direction = .right
        view.addGestureRecognizer(swipeRight)

        let swipeleft = UISwipeGestureRecognizer(target: self,action: #selector(self.respondToSwipeGesture))
        swipeleft.direction = .left
        view.addGestureRecognizer(swipeleft)

    }

// MARK: Table View Data Source

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

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

    func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "PlayTableViewCell"
        guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier,for: indexPath) as? PlayTableViewCell else {
            fatalError("The dequeued cell is not an instance of PlayTableViewCell.")
        }

        // Configure the cell...
        cell.wordLabel.text = words[indexPath.row]

        cell.wordLabel.isHidden = !(indexPath.row <= numberOfRevealedLabels - 1)

        return cell
    }

    @objc func respondToSwipeGesture(gesture: UIGestureRecognizer) {
        if let swipeGesture = gesture as? UISwipeGestureRecognizer {
            switch swipeGesture.direction {
            case UISwipeGestureRecognizer.Direction.right:
                indexGA = numberOfRevealedLabels
                numberOfRevealedLabels += 1
                numberOfGoodAnswers += 1
                playTableView.reloadData()
            case UISwipeGestureRecognizer.Direction.left:
                indexWA = numberOfRevealedLabels
                numberOfRevealedLabels += 1
                numberOfWrongAnswers += 1
                playTableView.reloadData()
            default:
                break
            }
        }
    }
}

PlayTableViewCell.swift

class PlayTableViewCell: UITableViewCell {

    //MARK: Properties
    @IBOutlet weak var wordLabel: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code

        wordLabel.lineBreakMode = .byWordWrapping;
        wordLabel.numberOfLines = 0;
        wordLabel.isHidden = true

    }

    override func setSelected(_ selected: Bool,animated: Bool) {
        super.setSelected(selected,animated: animated)

        // Configure the view for the selected state

    }

}

ListViewController.swift

class ListViewController: UIViewController,UITextFieldDelegate {

    @IBOutlet weak var titleTextField: UITextField!
    @IBOutlet weak var nametextField: UITextField!
    @IBOutlet weak var dataTableView: UITableView!
    @IBOutlet weak var saveButton: UIBarButtonItem!

    var data = [String]()

    //MARK: Properties
    var list: List?

    //MARK: ViewDidLoad
    override func viewDidLoad() {
        super.viewDidLoad()

        // Handle the text field’s user input through delegate callbacks.
        titleTextField.delegate = self
        nametextField.delegate = self

        // Set up views if editing an existing List.
        if let list = list {
            navigationItem.title = list.name
            titleTextField.text = list.name
            data = list.content
        }

        // Enable the Save button only if the title field has a valid List name
        updateSaveButtonState()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBaction func addNameToTable(_ sender: Any) {

        guard let word = nametextField.text else {
            return
        }
        data.append(word)
        dataTableView.reloadData()
    }

    @IBaction func playGame(_ sender: Any) {

    }

    //MARK: UITextFieldDelegate

    func textFieldDidBeginEditing(_ textField: UITextField) {

        // Disable the Save button while editing
        if (textField == titleTextField) {
            saveButton.isEnabled = false
        } else {
            saveButton.isEnabled = true
        }

    }

    func textFieldDidEndEditing(_ textField: UITextField) {

        updateSaveButtonState()
        navigationItem.title = titleTextField.text

        guard let word = nametextField.text else {
            return
        }

        if (textField == nametextField) {
            data.append(word)
            dataTableView.reloadData()
        }
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {

        // Hide the keyboard.
        textField.resignFirstResponder()
        return true
    }

    //MARK: Navigation

    @IBaction func cancel(_ sender: UIBarButtonItem) {

        // Depending on style of presentation (modal or push presentation),this view controller needs to be dismissed in two different ways.
        let isPresentingInAddListMode = presentingViewController is UINavigationController

        if isPresentingInAddListMode {

            dismiss(animated: true,completion: nil)
        } else if let owningNavigationController = navigationController{
            owningNavigationController.popViewController(animated: true)
        } else {
            fatalError("The ListViewController is not inside a navigation controller.")
        }
    }

    // This method lets you configure a view controller before it's presented.
    override func prepare(for segue: uistoryboardSegue,sender: Any?) {

        if (segue.identifier == "playGame") {

            // Passing words list to the PlayViewController
            let detailVC = segue.destination as! PlayViewController;
            detailVC.words = data
        }

        super.prepare(for: segue,sender: sender)

        // Configure the destination view controller only when the save button is pressed.

        guard let button = sender as? UIBarButtonItem,button === saveButton else {
            os_log("The save button was not pressed,cancelling",log: OSLog.default,type: .debug)
            return
        }

        let name = titleTextField.text ?? ""

        list = List(name: name,content: data)
    }

    //MARK: Private Methods

    private func updateSaveButtonState() {
        // Disable the Save button if the text field is empty.
        let name = titleTextField.text ?? ""
        saveButton.isEnabled = !name.isEmpty
    }
}

//MARK: Extension

extension ListViewController : UITableViewDelegate,UITableViewDataSource{

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }// Default is 1 if not implemented

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


    func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
        cell!.textLabel?.text = data[indexPath.row]
        return cell!
    }

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

    func tableView(_ tableView: UITableView,canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }

    func tableView(_ tableView: UITableView,editactionsForRowAt indexPath: IndexPath) -> [UITableViewRowaction]? {
        let editaction = UITableViewRowaction(style: .default,title: "Edit",handler: { (action,indexPath) in
            let alert = UIAlertController(title: "",message: "Edit list item",preferredStyle: .alert)
            alert.addTextField(configurationHandler: { (textField) in
                textField.text = self.data[indexPath.row]
            })
            alert.addaction(UIAlertaction(title: "Update",style: .default,handler: { (updateaction) in
                self.data[indexPath.row] = alert.textFields!.first!.text!
                self.dataTableView.reloadrows(at: [indexPath],with: .fade)
            }))
            alert.addaction(UIAlertaction(title: "Cancel",style: .cancel,handler: nil))
            self.present(alert,animated: false)
        })

        let deleteaction = UITableViewRowaction(style: .default,title: "Delete",indexPath) in
            self.data.remove(at: indexPath.row)
            self.dataTableView.reloadData()
        })

        return [deleteaction,editaction]
    }
}

它工作正常。

现在,我想在words中用tableView提示tableView FIFO样式(先进先出) 的每个项目固定数量的行。

假设我有3行func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int { return 3 }

words

word1 word2 word3 word4 word5 包含5个项目:

   First word      Second word        Third word       Fourth word        Fifth word

 ------------      ------------      ------------      ------------      ------------
|   word1    |    |   word1    |    |   word1    |    |   word2    |    |   word3    |
 ------------      ------------      ------------      ------------      ------------
|            |    |   word2    |    |   word2    |    |   word3    |    |   word4    |
 ------------      ------------      ------------      ------------      ------------
|            |    |            |    |   word3    |    |   word4    |    |   word5    |
 ------------      ------------      ------------      ------------      ------------

我想按以下顺序显示它们:

tableView

我需要在 PlayViewController.swift 中进行哪些更改才能重新创建此FIFO动画?

我在这里的目标是消除滚动并使其更易于阅读,并且还有助于在通过可滚动的{ "interface": "abc","entity": "def","attribute": [{ "name": "xyz","type": "int"}] } 执行时似乎无法检测到的滑动。

我不确定是否需要重写代码的大部分或者在 PlayViewController.swift 中更改几行可以解决问题。

感谢您的帮助!

lxt2015 回答:如何在UITableView中实现“先进先出”方法?

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/2852875.html

大家都在问