如何单击位于表格视图单元格外部的按钮来展开表格视图单元格?

时间:2019-02-20 08:31:43

标签: swift

有一个tableview单元格,还有一个更多按钮位于tableview上而不是该单元格中,因此我希望当项目运行时,它在tableview单元格中仅显示五个用户数据,而当用户单击更多按钮(位于单元格外部)如何实现?

感谢帮助

您可以找到原型细胞图像

here

// Mark:TableViewDelegate

extension MembersViewController:UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return imgarray.count
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tblView.dequeueReusableCell(withIdentifier: "membTableCell", for: indexPath) as! membTableCell
        cell.profiletabImg.image = imgarray[indexPath.row]
        cell.namelbl.text        =  names[indexPath.row]
        cell.positionlbl.text    =    "Ceo of code with color"
        return cell
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 40
    }
    @IBAction func morebutton(sender:UIButton){

    }


    }

2 个答案:

答案 0 :(得分:0)

如果将数据添加到数组并调用tableview.reloadData()函数,则tableview会自动展开。

从Apple的文档中- “调用此方法可重新加载用于构造表的所有数据,包括单元格,节的页眉和页脚,索引数组等。为了提高效率,表视图仅重新显示那些可见的行。由于重新加载,表会收缩。当表视图的委托或数据源希望表视图完全重新加载其数据时,将调用此方法。不应在插入或删除行的方法中调用此方法,尤其是在动画中通过调用beginUpdates()和endUpdates()实现的代码块。”

    @IBAction func moreBtnPressed(_ sender: Any) {
        tableviewArray.append("Append your array with remaining items")
        tableview.reloadData()
    }

答案 1 :(得分:0)

如果未轻按更多按钮,则以numberOfRowsInSection方法返回5。 点击更多按钮后,重新加载表视图并以imgarray.count方法返回numberOfRowsInSection

class TableViewController: UITableViewController {

    var dataArr = [String]()
    var expanded = false

    override func viewDidLoad() {
        super.viewDidLoad()
        dataArr = (1..<25).map({ String($0) })
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "\(dataArr.count - 5) more", style: .plain, target: self, action: #selector(morebutton(_:)))
    }
    @objc func morebutton(_ sender: UIBarButtonItem) {
        self.navigationItem.rightBarButtonItem = nil
        expanded = true
        tableView.reloadData()
    }
    // MARK: - Table view data source
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if !expanded && !dataArr.isEmpty {
            return 5
        } else {
            return dataArr.count
        }
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier") ?? UITableViewCell(style: .default, reuseIdentifier: "reuseIdentifier")
        cell.textLabel?.text = dataArr[indexPath.row]
        return cell
    }
}