ios - TableView限制使用(Swift)

标签 ios swift xcode uitableview swift3

你好,我有两个 View Controller ,第一个带有步进器

var steppers : UIStepper?
@IBOutlet weak var hourLabel: UILabel!

@IBAction func stepper(_ sender: UIStepper) {

      hourLabel.text = String(sender.value)
    }

第二个带有 tableView

import UIKit
import AVFoundation

class SelectClass: UIViewController, UITableViewDelegate, UITableViewDataSource  {


    @IBOutlet weak var tableView: UITableView!

    var list : [QCategoryy] = [QCategoryy]()
    var audioPlayer : AVAudioPlayer!
    var limit = 3


    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
        tableView.allowsMultipleSelection = true
        self.title = "Categories"
        list = NearbyPlaces.getCategories()




    }



    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)


        list.sort() { $0.views > $1.views}
        tableView.reloadData()
    }


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



  @IBAction func backTapp(_ sender: Any) {

        let audioUrl = NSURL.fileURL(withPath: Bundle.main.path(forResource: "pop_drip", ofType: "m4a")!)
        do{
            try AVAudioSession.sharedInstance().setActive(true)
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)

            try audioPlayer = AVAudioPlayer(contentsOf: audioUrl)
            audioPlayer.prepareToPlay()
            audioPlayer.play()
        }
        catch _ as NSError
        {

        }
        dismiss(animated: true, completion: nil)

    }


    @IBAction func doneTapp(_ sender: Any) {

        let audioUrl = NSURL.fileURL(withPath: Bundle.main.path(forResource: "pop_drip", ofType: "m4a")!)
        do{
            try AVAudioSession.sharedInstance().setActive(true)
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)

            try audioPlayer = AVAudioPlayer(contentsOf: audioUrl)
            audioPlayer.prepareToPlay()
            audioPlayer.play()
        }
        catch _ as NSError
        {

        }




        self.performSegue(withIdentifier: nearbySearchSegueIdentifier, sender: nil)
}




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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identifier = "CATEGORY_CELL"
        let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
        let selectedIndexPaths = tableView.indexPathsForSelectedRows
        let rowIsSelected = selectedIndexPaths != nil && selectedIndexPaths!.contains(indexPath)
       /* cell.accessoryType = rowIsSelected ? .checkmark : .none  */
        cell.accessoryType = list[indexPath.row].isSelected ? .checkmark : .none
        cell.textLabel?.text = list[indexPath.row].name
        return cell
    }

    let nearbySearchSegueIdentifier = "goToMcourse"

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

       let cell = tableView.cellForRow(at: indexPath)!
        cell.accessoryType = .checkmark


     /*   self.performSegue(withIdentifier: nearbySearchSegueIdentifier, sender: list[indexPath.row])  */
    }

    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {

       let cell = tableView.cellForRow(at: indexPath)!
        cell.accessoryType = .none

    }


    func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
        if let sr = tableView.indexPathsForSelectedRows {
            if sr.count == limit {
                let alertController = UIAlertController(title: "Oops", message:
                    "You are limited to \(limit) selections", preferredStyle: .alert)
                alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: {action in
                }))
                self.present(alertController, animated: true, completion: nil)

                return nil
            }
        }

        return indexPath


        }





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

        if segue.identifier == nearbySearchSegueIdentifier {
            guard let category = sender as? QCategoryy else {
                return
            }
            if let selectedRows = tableView.indexPathsForSelectedRows {

                if let vc = segue.destination as? CourseClass2 {
                vc.category = category
            }
        }
    }
}


}




    extension QCategoryy {
    private static let ketPrefix = "category-"

    var views:Int {
        get {
            return UserDefaults.standard.integer(forKey: QCategoryy.ketPrefix + name)
        }
    }

    func markView() {
        UserDefaults.standard.set(views + 1, forKey: QCategoryy.ketPrefix + name)
    }
}

在此 tableView 中,我可以选择多个单元格并使用 var 添加对选择的限制

var limit = 3

和函数

 func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
        if let sr = tableView.indexPathsForSelectedRows {
            if sr.count == limit {
                let alertController = UIAlertController(title: "Oops", message:
                    "You are limited to \(limit) selections", preferredStyle: .alert)
                alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: {action in
                }))
                self.present(alertController, animated: true, completion: nil)

                return nil
            }
        }

        return indexPath


        }

但我想做的是使用第一个 viewController 中的步进器在选择 tableView (在第二个 viewController 中)时添加限制,例如 enter image description here

enter image description here

我该怎么做?

最佳答案

在带有步进器的 VC 中,覆盖 prepareForSegue:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let vc = segue.destination as? SelectClass {
        vc.limit = Int(stepper.value)
    }
}

编辑:您需要使步进器成为 VC 的导出,首先将声明更改为:

@IBOutlet var stepper: UIStepper!

在 Storyboard中,右键单击 View Controller (带有黄色图标的 Controller ):

enter image description here

然后出现:

enter image description here

看到“ socket ”下的步进器了吗?从步进器旁边的圆圈拖动到 Storyboard 上的步进器:

enter image description here

关于ios - TableView限制使用(Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46886275/

相关文章:

ios - 如何选择何时返回 Collection View 单元格

ios - 如何在 Swift 3.0 中一段时间​​后插入警报

ios - 触摸屏幕区域关闭 View Controller

iphone - 加载文本时 UITextView.text 滞后

swift - 快速检查空引用 Firebase swift

ios - 缺少代码签名权利 - 在 bundle 'com.google.Googleplus' 中找不到任何权利

ios - TableView 数据未显示在 iOS6 和 Xcode 的新 Storyboard场景中

ios - OBJ-C-正在检测textView换行吗?

ios - Swift,解码 "iso-8859-5"

ios - UI 开关保存位置 NSSUser defaults 仅在手动切换时有效