【问题标题】:Click on UIButton outside table view change in tableview cell text在表格视图单元格文本中单击表格视图更改之外的 UIButton
【发布时间】:2017-07-14 09:27:13
【问题描述】:

我是 IOS 新手,我想在 swift 中从 tableView 外部创建一个表格视图和一个 UIButton

我想点击UIButton,然后更改UITableViewCell 的文字。

【问题讨论】:

  • 如果功能是更改特定的单元格数据,那么您必须使单元格中的按钮也成为单元格的类。您可以提供一些草图来帮助我们解决问题。

标签: swift button tableview


【解决方案1】:

我会创建新的UIViewController。在此视图控制器中创建UITableView 属性和UIButton 属性,并在视图控制器的初始化中创建新的UITableView 并分配给此属性,UIButton 相同。

实现tableViewDelegatetableViewDatasource 方法。

viewDidLoad() 你需要做一些布局。例如在前半部分适合表格视图,以及在表格视图下的按钮。

在按钮操作中,您可以更改呈现 tableView 的 dataModel。 (在方法cellForRowAtIndexPath中)

毕竟您需要调用tableView.reloadData() 并触发方法cellForRowAtIndexPath 并根据更新的数据模型重新渲染表。

最小代码示例 在此代码示例中,UIButton 不在 tableView 下,而是在 navigationBar 中。整个控制器也是 UITableViewController 的子类,而不是将 tableView 添加到 UIViewController。我只是想让它尽可能简单。

//
//  MasterViewController.swift
//  stackOverflow
//
//  Created by Jakub Prusa on 14.07.17.
//  Copyright © 2017 Jakub Prusa. All rights reserved.
//

import UIKit


class MasterViewController: UITableViewController {

    var dataModel = ["AAA","BBB","CCC","DDD",]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(modifyDataModel(_:)))
        navigationItem.rightBarButtonItem = addButton

    }

    // MARK: - Button action
    func modifyDataModel(_ sender: Any) {
        dataModel[2] = "xx_CCC_xx"
        tableView.reloadData()
    }

    // MARK: - Table View

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

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

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

        cell.textLabel!.text = dataModel[indexPath.row] 
        return cell
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    • 2015-05-07
    • 1970-01-01
    • 2018-11-17
    相关资源
    最近更新 更多