简体   繁体   中英

Adding an item to a cell in tableview by clicking a button swift ios

I am trying to add an item in tableview cell ie appending an item to last of tableview cell. I have looked at different answers on stackoverflow but none helped me I analyzed THIS ANSWER . I have four arrays and four cells those are combined in a table view to a segmented control

this code gives me error and terminates:

Index out of range

at line secCell.textLabel?.text = secArray[indexPath.row]

What I want is :

I want to add more cells and inside every cell I want to store the each item

import UIKit

@available(iOS 11.0, *)
class MainTableFormViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

var firstArray = [String]()
var secArray = [String]()
var thirdArray = [String]()
var fourthArray = [String]()

var selectedSegment = 1

@IBAction func insertButton(_ sender: Any) {

     let item = "A new item"
    firstArray.append(item)

    firstTableView.beginUpdates()

    let indexPath:IndexPath = IndexPath(row:(self.firstArray.count - 1), section:0)

    firstTableView.insertRows(at: [indexPath], with: .left)

    TableView.endUpdates()


    firstTableView.insertRows(at: [IndexPath(row: firstArray.count - 1, section: 0)], with: .automatic) //row param is 0 for first row
    firstTableView.endUpdates()

    firstTableView.scrollToRow(at: indexPath, at: .bottom, animated: true)


    DispatchQueue.main.async {
        self.firstTableView.reloadData()
        print("row added")
   }

    print(firstArray)
}

@IBOutlet weak var cancelMainTabForm: UIBarButtonItem!

@IBAction func cancelMainTabFormAct(_ sender: Any) {
    _ = navigationController?.popViewController(animated: true)
}

@IBOutlet weak var createMainTabForm: UIBarButtonItem!

@IBAction func createMainTabForm(_ sender: Any) {
}

@IBAction func mainSegment(_ sender: UISegmentedControl) {

    if sender.selectedSegmentIndex == 0 {
        selectedSegment = 1
    }
    if sender.selectedSegmentIndex == 1 {
        selectedSegment = 2
    }
    if sender.selectedSegmentIndex == 2 {
        selectedSegment = 3
    }
    if sender.selectedSegmentIndex == 3 {
        selectedSegment = 4
    }
    firstTableView.reloadData()

}

@IBOutlet weak var firstTableView: UITableView!


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if selectedSegment == 1 {
    return firstArray.count
    }
    if selectedSegment == 2 {
        return secArray.count
    }
    if selectedSegment == 3 {
        return thirdArray.count
    }
    else {
        return fourthArray.count
    }
}

@IBOutlet weak var tempTitle: UIButton!



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

    let firstCell = firstTableView.dequeueReusableCell(withIdentifier: "firstCell")! as UITableViewCell
    let secCell = firstTableView.dequeueReusableCell(withIdentifier: "secCell")! as UITableViewCell
    let thirdCell = firstTableView.dequeueReusableCell(withIdentifier: "thirdCell")! as UITableViewCell
    let fourthCell = firstTableView.dequeueReusableCell(withIdentifier: "fourthCell")! as UITableViewCell
    firstCell.textLabel?.text = firstArray[indexPath.row]
    secCell.textLabel?.text = secArray[indexPath.row]
    thirdCell.textLabel?.text = thirdArray[indexPath.row]
    fourthCell.textLabel?.text = fourthArray[indexPath.row]

    if selectedSegment == 1 {

        return firstCell
    }
    if selectedSegment == 2 {

        return secCell
    }
    if selectedSegment == 3 {

        return thirdCell
    }
    else  {

        return fourthCell
    }

}




func moveToViewVC() {
    let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle : nil)
    let desController = mainStoryBoard.instantiateViewController(withIdentifier: "ViewViewController") as! ViewViewController
    let newFrontViewController = UINavigationController.init(rootViewController:desController)
    revealViewController().pushFrontViewController(newFrontViewController, animated: true)
}


override func viewDidLoad() {
    super.viewDidLoad()

    firstArray = ["a", "b", "c", "d", "e"]
    secArray = ["1", "2", "3", "4", "5"]
    thirdArray = ["ww", "ww", "c", "d", "e"]
    fourthArray = ["kk", "kk", "3", "4", "5"]

    firstTableView.delegate = self
    firstTableView.dataSource = self

    navigationController?.navigationBar.barTintColor = UIColor(red:0.00, green:0.52, blue:1.00, alpha:1.0)
    navigationController?.navigationBar.tintColor = UIColor.white

    let vcR : ViewViewController = ViewViewController()
    let temptitleText = vcR.getFormId
    print(temptitleText)

    if getTempTitleTextName?.isEmpty == false {
    tempTitle.setTitle(getTempTitleTextName, for: .normal)
} else {
    print("this is temp tiltele \(temptitleText)")
}

}

var getTempTitleTextName : String?

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

}

在此处输入图片说明

You should do like this way,

@IBAction func insertButton(_ sender: Any) {
    let item = "A new item"

    firstTableView.beginUpdates()
    firstArray.append(item)
    let indexPath:IndexPath = IndexPath(row:(self.firstArray.count - 1), section:0)
    firstTableView.insertRows(at: [indexPath], with: .left)
    firstTableView.endUpdates()

    print(firstArray)
}

try updating your this method,

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let firstCell = firstTableView.dequeueReusableCell(withIdentifier: "firstCell")! as UITableViewCell
    let secCell = firstTableView.dequeueReusableCell(withIdentifier: "secCell")! as UITableViewCell
    let thirdCell = firstTableView.dequeueReusableCell(withIdentifier: "thirdCell")! as UITableViewCell
    let fourthCell = firstTableView.dequeueReusableCell(withIdentifier: "fourthCell")! as UITableViewCell

    if selectedSegment == 1 {
        firstCell.textLabel?.text = firstArray[indexPath.row]
        return firstCell
    } else if selectedSegment == 2 {
        secCell.textLabel?.text = secArray[indexPath.row]
        return secCell
    } else if selectedSegment == 3 {
        thirdCell.textLabel?.text = thirdArray[indexPath.row]
        return thirdCell
    } else  {
        fourthCell.textLabel?.text = fourthArray[indexPath.row]
        return fourthCell
    }
}

UPDATE

you need to do like this way,

@IBAction func insertButton(_ sender: Any) {
    let item = "A new item"
    firstArray.append(item)
    firstTableView.reloadData()
}

this works for me, let me know in case of any queries.

Since you are already calling firstTableView.reloadData()

You can try this

    import UIKit

@available(iOS 11.0, *)
class MainTableFormViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

var firstArray = [String]()
var secArray = [String]()
var thirdArray = [String]()
var fourthArray = [String]()

var selectedSegment = 1

@IBAction func insertButton(_ sender: Any) {

     let item = "A new item"
    firstArray.append(item)

    firstTableView.beginUpdates()

    let indexPath:IndexPath = IndexPath(row:(self.firstArray.count - 1), section:0)

    firstTableView.insertRows(at: [indexPath], with: .left)

    TableView.endUpdates()


    firstTableView.insertRows(at: [IndexPath(row: firstArray.count - 1, section: 0)], with: .automatic) //row param is 0 for first row
    firstTableView.endUpdates()

    firstTableView.scrollToRow(at: indexPath, at: .bottom, animated: true)


    DispatchQueue.main.async {
        self.firstTableView.reloadData()
        print("row added")
   }

    print(firstArray)
}

@IBOutlet weak var cancelMainTabForm: UIBarButtonItem!

@IBAction func cancelMainTabFormAct(_ sender: Any) {
    _ = navigationController?.popViewController(animated: true)
}

@IBOutlet weak var createMainTabForm: UIBarButtonItem!

@IBAction func createMainTabForm(_ sender: Any) {
}

@IBAction func mainSegment(_ sender: UISegmentedControl) {

    if sender.selectedSegmentIndex == 0 {
        selectedSegment = 1
    }
    if sender.selectedSegmentIndex == 1 {
        selectedSegment = 2
    }
    if sender.selectedSegmentIndex == 2 {
        selectedSegment = 3
    }
    if sender.selectedSegmentIndex == 3 {
        selectedSegment = 4
    }
    firstTableView.reloadData()

}

@IBOutlet weak var firstTableView: UITableView!


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if selectedSegment == 1 {
    return firstArray.count
    }
    if selectedSegment == 2 {
        return secArray.count
    }
    if selectedSegment == 3 {
        return thirdArray.count
    }
    else {
        return fourthArray.count
    }
}

@IBOutlet weak var tempTitle: UIButton!



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

    var cell: UITableViewCell;

    if selectedSegment == 1 {
        cell = firstTableView.dequeueReusableCell(withIdentifier: "firstCell")! as UITableViewCell
        firstCell.textLabel?.text = firstArray[indexPath.row]

    }
    if selectedSegment == 2 {
        cell = firstTableView.dequeueReusableCell(withIdentifier: "secCell")! as UITableViewCell
        secCell.textLabel?.text = secArray[indexPath.row]

    }
    if selectedSegment == 3 {
        cell = firstTableView.dequeueReusableCell(withIdentifier: "thirdCell")! as UITableViewCell
        thirdCell.textLabel?.text = thirdArray[indexPath.row]

    }
    else  {
        cell = firstTableView.dequeueReusableCell(withIdentifier: "fourthCell")! as UITableViewCell
        fourthCell.textLabel?.text = fourthArray[indexPath.row]

    }

    return cell;
}




func moveToViewVC() {
    let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle : nil)
    let desController = mainStoryBoard.instantiateViewController(withIdentifier: "ViewViewController") as! ViewViewController
    let newFrontViewController = UINavigationController.init(rootViewController:desController)
    revealViewController().pushFrontViewController(newFrontViewController, animated: true)
}


override func viewDidLoad() {
    super.viewDidLoad()

    firstArray = ["a", "b", "c", "d", "e"]
    secArray = ["1", "2", "3", "4", "5"]
    thirdArray = ["ww", "ww", "c", "d", "e"]
    fourthArray = ["kk", "kk", "3", "4", "5"]

    firstTableView.delegate = self
    firstTableView.dataSource = self

    navigationController?.navigationBar.barTintColor = UIColor(red:0.00, green:0.52, blue:1.00, alpha:1.0)
    navigationController?.navigationBar.tintColor = UIColor.white

    let vcR : ViewViewController = ViewViewController()
    let temptitleText = vcR.getFormId
    print(temptitleText)

    if getTempTitleTextName?.isEmpty == false {
    tempTitle.setTitle(getTempTitleTextName, for: .normal)
} else {
    print("this is temp tiltele \(temptitleText)")
}

}

var getTempTitleTextName : String?

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

}

You need to update data source array whenever you are inserting item in table view and after that add it in table view.

firstArray.append(item)
let indexPath:IndexPath = IndexPath(row:self.firstArray.count - 1, section:0)
firstTableView.insertRows(at: [indexPath], with: .automatic)

I tried all but no answer helped me, finally done this way:

 @IBAction func insertButton(_ sender: Any) {   

    if selectedSegment == 1 {

        let item = "A new item"
        firstArray.append(item)
        firstTableView.reloadData()
    }
    if selectedSegment == 2 {

        let item = "A new item"
        secArray.append(item)
        firstTableView.reloadData()
    }
    if selectedSegment == 3 {

        let item = "A new item"
        thirdArray.append(item)
        firstTableView.reloadData()
    }
    if selectedSegment == 4 {

        let item = "A new item"
        fourthArray.append(item)
        firstTableView.reloadData()
    }
}

and changed the method as :

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

    let firstCell = firstTableView.dequeueReusableCell(withIdentifier: "firstCell")! as UITableViewCell
    let secCell = firstTableView.dequeueReusableCell(withIdentifier: "secCell")! as UITableViewCell
    let thirdCell = firstTableView.dequeueReusableCell(withIdentifier: "thirdCell")! as UITableViewCell
    let fourthCell = firstTableView.dequeueReusableCell(withIdentifier: "fourthCell")! as UITableViewCell


    if selectedSegment == 1 {
      firstCell.textLabel?.text = firstArray[indexPath.row]
        return firstCell
    }
    if selectedSegment == 2 {
        secCell.textLabel?.text = secArray[indexPath.row]
        return secCell
    }
    if selectedSegment == 3 {
    thirdCell.textLabel?.text = thirdArray[indexPath.row]
        return thirdCell
    }
    else  {
      fourthCell.textLabel?.text = fourthArray[indexPath.row]
        return fourthCell
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM