ios - TableView崩溃了,为什么它还是这样竖着呢?

标签 ios swift uitableview

我正在设置一个可折叠的 tableView,但可折叠项目上发生了一些奇怪的事情。当您观看视频时,请注意“您所在位置”这一行。(我使用 .plist 作为问题和答案项目)

我哪里出错了,是在我的代码中的某个地方吗?我不想让那条线粘在顶部:(

enter image description here

这是我正在使用的代码,但我找不到任何奇怪的东西......

class FAQViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    var questionsArray = [String]()
    var answersDict = Dictionary<String, [String]>() // multiple answers for a question
    var collapsedArray = [Bool]()
    
    @IBOutlet weak var tableView: UITableView!
    
    override func viewWillAppear(_ animated: Bool) {
        // Hide the navigation bar on the this view controller
        self.navigationController?.setNavigationBarHidden(true, animated: true)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        addTableStyles()
        readQAFile()
        
        tableView.delegate = self
        tableView.dataSource = self
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
    }
    
    func addTableStyles(){
        navigationController?.isNavigationBarHidden = false
        
        self.tableView?.backgroundView = {
            let view = UIView(frame: self.tableView.bounds)
            return view
        }()
        
        tableView.estimatedRowHeight = 43.0;
        tableView.rowHeight = UITableView.automaticDimension
        tableView.separatorStyle = UITableViewCell.SeparatorStyle.singleLine
    }
    
    func readQAFile(){
        guard let url = Bundle.main.url(forResource: "QA", withExtension: "plist")
            else { print("no QAFile found")
                return
        }
        
        let QAFileData = try! Data(contentsOf: url)
        let dict = try! PropertyListSerialization.propertyList(from: QAFileData, format: nil) as! Dictionary<String, Any>
        
        // Read the questions and answers from the plist
        questionsArray = dict["Questions"] as! [String]
        answersDict = dict["Answers"] as! Dictionary<String, [String]>
        
        // Initially collapse every question
        for _ in 0..<questionsArray.count {
            collapsedArray.append(false)
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return questionsArray.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        if collapsedArray[section] {
            let ansCount = answersDict[String(section)]!
            return ansCount.count
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        // Set it to any number
        return 70
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if collapsedArray[indexPath.section] {
            return UITableView.automaticDimension
        }
        return 2
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let headerView = UIView(frame: CGRect(x:0, y:0, width:tableView.frame.size.width, height:40))
        headerView.tag = section
        
        let headerString = UILabel(frame: CGRect(x: 10, y: 10, width: tableView.frame.size.width, height: 50)) as UILabel
         headerString.text = "\(questionsArray[section])"
        headerView .addSubview(headerString)
        
        let headerTapped = UITapGestureRecognizer (target: self, action:#selector(sectionHeaderTapped(_:)))
        headerView.addGestureRecognizer(headerTapped)
        
        return headerView
    }
    
    @objc func sectionHeaderTapped(_ recognizer: UITapGestureRecognizer) {
        
        let indexPath : IndexPath = IndexPath(row: 0, section:recognizer.view!.tag)
        if (indexPath.row == 0) {
            
            let collapsed = collapsedArray[indexPath.section]
            
            collapsedArray[indexPath.section] = !collapsed
            
            //reload specific section animated
            let range = Range(NSRange(location: indexPath.section, length: 1))!
            let sectionToReload = IndexSet(integersIn: range)
            self.tableView.reloadSections(sectionToReload as IndexSet, with:UITableView.RowAnimation.fade)
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        
        let cellIdentifier = "Cell"
        let cell: UITableViewCell! = self.tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
        
        cell.textLabel?.adjustsFontSizeToFitWidth = true
        cell.textLabel?.numberOfLines = 0
        
        let manyCells : Bool = collapsedArray[indexPath.section]
        
        if (manyCells) {
            let content = answersDict[String(indexPath.section)]
            cell.textLabel?.text = content![indexPath.row]
        }
        
        return cell
    }
    
    override var prefersStatusBarHidden: Bool {
        return true
    }
    
}

最佳答案

需要将tableView的样式改为grouped ,当你初始化它时:

let tableView = UITableView(frame: someFrame, style: .grouped)

或来自 Storyboard:

enter image description here

之后您将拥有this issue ,我通过将 tableHeaderView 设置为以 CGFloat.leastNormalMagnitude 作为其 height 的 tableView 来解决这个问题:

override func viewDidLoad() {
    super.viewDidLoad()
    
    var frame = CGRect.zero
    frame.size.height = .leastNormalMagnitude
    tableView.tableHeaderView = UIView(frame: frame)
}

关于ios - TableView崩溃了,为什么它还是这样竖着呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64626149/

相关文章:

ios - 防止 NSManagedObject 引用更新 UITableViewCell

swift - 如何在 UITableView 内的 UITabBar 顶部添加 UIButton

ios - 如何修复 iOS 7 中的状态栏重叠问题

ios - 在两个贝塞尔路径形状之间制作动画

ios - 使用按钮展开/折叠 tableView 单元格,并在单元格展开时显示 View 中的其他元素

swift - 复制或赋值时,swift 深层数组如何复制自身

ios - 如何在 UITableViewCell 中重用 UIView 的 xib 子类

html - CSS 背景在 Safari 上会拉伸(stretch)以填满屏幕,但在 iOS 上不会

android - 无法为 React Native (iOS) 创建离线包

ios - 在 iPhone 应用程序中实现应用程序瘦身