Swift:-在自定义tableview单元格中单击按钮时将标签值增加1

时间:2018-10-31 05:06:53

标签: swift uitableview swift4

我试图在自定义表格单元格内单击按钮时将标签值增加1。我能够在不同的单元格中以不同的方式更改值,但是问题是,如果我在第一个单元格标签中点按+从0更改为1,当我在第二个单元格标签中点按+直接从0更改为2,以此类推。我该如何解决?

<html>
<head>
    <title>Leaflet geolocate example</title>
    
   
    <link href="https://unpkg.com/leaflet@1.3.4/dist/leaflet.css" rel="stylesheet" />
    <link href="https://unpkg.com/leaflet.markercluster@1.4.1/dist/MarkerCluster.Default.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://unpkg.com/leaflet.gridlayer.googlemutant@latest/Leaflet.GoogleMutant.js"></script>
    <script src="https://unpkg.com/leaflet@1.3.4/dist/leaflet.js"></script>
    <script src="https://unpkg.com/leaflet.markercluster@1.4.1/dist/leaflet.markercluster-src.js"></script>
    <script language="javascript">
        var map;
        var markers = [];
       

        function init() {

          
            var map = new L.Map('test_map', {

                fullscreenControl: {
                    pseudoFullscreen: false // if true, fullscreen to page width and height
                },

            }).setView([-40.99497, 174.50808], 10);

            map.createPane('labels');
            map.getPane('labels').style.zIndex = 650;
            map.getPane('labels').style.pointerEvents = 'none';

            var positron = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                noWrap: true,
                maxZoom: 15
            }).addTo(map);
               var positronLabels = L.tileLayer('http://{s}.basemaps.cartocdn.com/light_only_labels/{z}/{x}/{y}.png', {
                pane: 'labels',
                noWrap: true,
                maxZoom: 3
            }).addTo(map);


                 var southWest = L.latLng(-89.98155760646617, -180),
                northEast = L.latLng(89.99346179538875, 180),
                bounds = L.latLngBounds(southWest, northEast);

            map.setMaxBounds(bounds);
            map.on('drag', function () {
                map.panInsideBounds(bounds, { animate: false });
            });

                 var plot = [
                ["7C6B07", -40.99497, 174.50808],
                ["7C6B38", -41.30269, 173.63696],
                ["7C6CA1", -41.49413, 173.5421],
                ["7C6CA2", -40.98585, 174.50659],
                ["C81D9D", -40.93163, 173.81726],
                ["C82009", -41.5183, 174.78081],
                ["C82081", -41.42079, 173.5783],
                ["C820AB", -42.08414, 173.96632],
                ["C820AB", -42.08414, 173.96632]
            ];

            var markercluster = new L.MarkerClusterGroup();
            for (var i = 0; i < plot.length; i++) {
                marker = new L.marker([plot[i][1], plot[i][2]]).bindPopup(plot[i][0], { autoClose: false }).addTo(map).openPopup();
                markers.push(marker);
                markercluster.addLayer(marker);
            }
            markercluster.on('clusterclick', function (a) { alert('Cluster Clicked'); });
            map.addLayer(markercluster);
 

        }




    </script>

</head>
<body onLoad="javascript:init();">
    <div id="test_map" style="height: 500px"></div>
   

</body>
</html>

3 个答案:

答案 0 :(得分:3)

有两种方法可以实现这一目标:

1。。使Array级别的controller中每个单元格的计数保持不变,每次按button,从数组中获取计数并使用它,即

var counts = [Int](repeating: 0, count: 10) //10 is the number of cells here

@IBAction func addPressed(_ sender: UIButton) {
    let indexPath = IndexPath(row: sender.tag, section: 0)
    let cell = tblview.cellForRow(at: indexPath) as! HomeDetailsTableViewCell
    counts[indexPath.row] += 1
    cell.lblNoOfItems.text = "\(counts[indexPath.row])"
}

2。。将每个单元格的计数保留在自定义单元格本身中,即保存在HomeDetailsTableViewCell中,即

class HomeDetailsTableViewCell: UITableViewCell {
    var count = 0
    //Rest of the code...
}

@IBAction func addPressed(_ sender: UIButton) {
        let indexPath = IndexPath(row: sender.tag, section: 0)
        let cell = tblview.cellForRow(at: indexPath) as! HomeDetailsTableViewCell
        cell.count += 1
        cell.lblNoOfItems.text = "\(cell.count)"
}

此外,实现添加+ button的代码的方式也不正确。您必须在HomeDetailsTableViewCell本身内实现它,即

class HomeDetailsTableViewCell: UITableViewCell {
    @IBOutlet weak var lblNoOfItems: UILabel!
    var count = 0

    @IBAction func addPressed(_ sender: UIButton) {
        self.count += 1
        self.lblNoOfItems.text = "\(self.count)"
    }
    //Rest of the code...
}

答案 1 :(得分:0)

这是因为您要对类中的所有单元格使用全局变量,如果您希望对每个单元格保持不同的计数,则必须为每个单元格使用不同的变量,我只是给您指示,以便您找到自己的路线

创建一个用于计数的数据源,并使用与表所用的数据源相同的数据源进行初始化,例如,假设您的tableview数据源有一个字符串数组,则可以创建包含标题和计数的列表数组。我为您提供了解决方案中的所有步骤,您只需要将代码放在正确的位置即可:-

//Suppose this is your tableivew data source
let list : [String] = ["Title1","Title2","Title3"]

//Make a dictionary that is going to be your datasource of tableview holding the count too
var listDict : [[String:Any]] = []
for item in list{
    let dict : [String:Any] = ["title":item,"count":Int(0)]
    listDict.append(dict)
}

//Where you are performing the actions like in didSelectRow or in any button
let cellIndexPath : IndexPath = IndexPath(item: 0, section: 0) // Get the indexPath of Cell

//Update the count
if let count = listDict[cellIndexPath.row]["count"] as? Int{
    let newValue = count + 1
    listDict[cellIndexPath.row]["count"] = newValue
}

//Reload the tableview cell of update manually your choice I'm reloading the cell for short
let tableview = UITableView()
tableview.reloadRows(at: [cellIndexPath], with: .fade)

答案 2 :(得分:0)

您可以使用 Swift 5

中的以下代码获取此问题的答案

//第一步

TableViewCell

内部
import UIKit

@objc protocol CellDelagate : NSObjectProtocol {

    func addPressed(_ cell: TableViewCell)
}

class TableViewCell: UITableViewCell {

    var cellDelagate: CellDelagate?
    var indexPath : IndexPath?
    @IBOutlet weak var gPaybutton: UIButton!
    @IBOutlet weak var proceesingLabel: UILabel!

    var count = 0

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

    @IBAction func proccessingButtonTapped(_ sender: UIButton) {

        self.cellDelagate!.addPressed(self)
        if gPaybutton.tag == indexPath?.row {

        }
    }
}

//第二步

ViewController

内部
class ViewController: UIViewController {

    @IBOutlet weak var tableview: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
}

extension ViewController: UITableViewDataSource, UITableViewDelegate, CellDelagate {

    func addPressed(_ cell: TableViewCell) {

        cell.count += 1
        cell.proceesingLabel.text = "Processing : \(cell.count)"
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell")! as? TableViewCell//1.

        cell?.indexLabel?.text = yourArray[indexPath.row] //2.
        cell?.cellDelagate = self //3.
        cell?.tag = indexPath.row //4.
        return cell! //5.
    }
}
相关问题