I am working with a UITableView in a normal UIViewController. For some reason, the text of the top cell in my TableView is always colored gray.
I have been trying to figure out what causes that cell to be gray, but don't know what it is. The data in my tableView is sourced from an array called fileList that gets refreshed during both viewWillAppear and viewDidAppear.
Why is the top cell always gray with this code?
(And it does happen both with nothing in the fileList and with many things in the fileList)
//MARK: - TableView
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if fileList.count == 0 {
return 1
} else {
return fileList.count
}
}
internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if fileList.count == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.isUserInteractionEnabled = false
cell.accessoryType = UITableViewCellAccessoryType.none
cell.textLabel?.text = "No documents found"
cell.textLabel?.textAlignment = .center
cell.textLabel?.textColor = UIColor.black
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.isUserInteractionEnabled = true
cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
cell.textLabel?.text = (fileList[indexPath.row])
cell.textLabel?.textAlignment = .left
cell.textLabel?.textColor = UIColor.black
return cell
}
}
}
There is no issue running your code , It's running fine for me.
Even setting cell.selectionstyle = .grey is not putting grey color to cell or text.
You have to be more clear about question .
1) What is grey? text color or cell color.
2) What is the code that you are hiding or doing else apart?
extension ViewController : UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return fileList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
let rowData = fileList[indexPath.row]
cell?.textLabel?.text = rowData
//cell?.isSelected = true
cell?.selectionStyle = .gray
cell?.isUserInteractionEnabled = true
cell?.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
cell?.textLabel?.textAlignment = .left
cell?.textLabel?.textColor = UIColor.black // if let priceString = rowData[2] as? String { cell.priceLabel.text = "Price: $(priceString)" }
return cell!
}
// Number of sections in table
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}// Default is 1 if not implemented
}
I believe this is the same as the problem mentioned here. Try setting:
cell?.textLabel?.isEnabled = true`
in the if statement block for fileList.count == 0 after the line
cell.isUserInteractionEnabled = false
Related
I am facing this weird problem of updating a button in a cell on click. I have this like button which i change depend on status i get in response when i click the button. So when the like status is false. I show it in grey and on click if the status in back-end changes and if i get the status as true in response i change it to pink and vice- versa. The issue is for the first time. once i change the cell the functionality works as expected.
Here is my code
I made a variable for the cell to access it globally
var TheVideoPlayerCell:VideoPlayerCell?
func registerTableCells(){
myTable.register(UITableViewCell.self, forCellReuseIdentifier: "DefaultCell")
myTable.register(UINib(nibName: "VideoPlayerCell", bundle: nil), forCellReuseIdentifier: "VideoPlayerCell")
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return videoArrObj?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "VideoPlayerCell", for: indexPath) as! VideoPlayerCell
TheVideoPlayerCell = cell
cell.obj = videoArrObj?[indexPath.row]
cell.btn_Likes.addTarget(self, action: #selector(onClickLike), for: .touchUpInside)
cell.selectionStyle = .none
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return CGFloat(self.myTable.frame.height)
}
Once i get a response from backend
self.TheVideoPlayerCell?.btn_Likes.isEnabled = true
let obj = try JSONDecoder().decode(LikeStatusModal.self, from: data)
let likeStatus = obj.data?.like_status ?? false
let totalLikes = obj.data?.total_likes ?? ""
if likeStatus{
self.TheVideoPlayerCell?.btn_Likes.setImage(UIImage(named: "icon_like_selected"), for: .normal)
}else{
self.TheVideoPlayerCell?.btn_Likes.setImage(UIImage(named: "icon_like_unselected"), for: .normal)
}
if totalLikes != ""{
self.TheVideoPlayerCell?.lbl_NoOfLikes.text = totalLikes
}
self.TheVideoPlayerCell?.obj?.is_like = likeStatus
self.TheVideoPlayerCell?.obj?.likes = totalLikes
self.videoArrObj?[self.currentIndex].is_like = likeStatus
self.videoArrObj?[self.currentIndex].likes = totalLikes
You are getting the wrong indexpath. Try accessing the cell this way.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "VideoPlayerCell", for: indexPath) as! VideoPlayerCell
cell.obj = videoArrObj?[indexPath.row]
cell.btn_likes.tag = indexPath.row
cell.btn_Likes.addTarget(self, action: #selector(onClickLike(sender:)), for: .touchUpInside)
cell.selectionStyle = .none
return cell
}
func onClickLike(sender : UIButton) {
// Here is have the api request for that video obj
ServiceSuccessData(action : "YourString", data : Data, index : sender.tag)
}
//Once I get response from server
func ServiceSuccessData(action:String, data:Data, index : Int){
let cell = tableView.cellForRow(at: IndexPath(row: index, section: 0)) as! YourCell
cell.btn_Likes.isEnabled = true
DispatchQueue.main.async {
let obj = try JSONDecoder().decode(LikeStatusModal.self, from: data)
let likeStatus = obj.data?.like_status ?? false
let totalLikes = obj.data?.total_likes ?? ""
if likeStatus{
cell.btn_Likes.setImage(UIImage(named: "icon_like_selected"), for: .normal)
} else {
cell.btn_Likes.setImage(UIImage(named: "icon_like_unselected"), for: .normal)
}
if totalLikes != ""{
cell.lbl_NoOfLikes.text = totalLikes
}
cell.obj?.is_like = likeStatus
cell.obj?.likes = totalLikes
self.videoArrObj?[self.currentIndex].is_like = likeStatus
self.videoArrObj?[self.currentIndex].likes = totalLikes
}
}
I have Two Array of Int In which the Index Number is Stored and I want that IndexPath.row cell Background Colour Should Change accordingly.
let redCell = ["0","1","4"]
let greenCell = ["2","3"]
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "playQuizTableViewCell") as? playQuizTableViewCell
if indexPath.row == redCell {
cell?.textLabel?.backgroundColor = UIColor.red
} else if indexPath.row == greenCell{
cell?.textLabel?.backgroundColor = UIColor.green
} else {
cell?.textLabel?.backgroundColor = UIColor.black
}
}
I want to change cell colour of indexPath.row which is matching inside the array.
Please Guide me.
Thanks
First, make your arrays into arrays of Int instead of String.
let redCell = [0, 1, 4]
let greenCell = [2, 3]
Now update your cellForRowAt to check if indexPath.row is in a given array:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "playQuizTableViewCell") as! playQuizTableViewCell
if redCell.contains(indexPath.row) {
cell.textLabel?.backgroundColor = .red
} else if greenCell.contains(indexPath.row) {
cell.textLabel?.backgroundColor = .green
} else {
cell?.textLabel?.backgroundColor = .black
}
}
I do know how to input background colours for my row, but I don't really know how I can filter it by only the bottom 5 rows are "cell.backgroundColor = UIColor.red;" whereas the rest stays the same. Appreciate those who can help me this thanks!
P.S: Sorry as my swift is quite rusty.
UITableView Controller
import UIKit
import FirebaseDatabase
var postData2 = [String]()
var postData3 = [String]()
var tableDataArray = [tableData]()
class ResultsController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
ref = Database.database().reference() //set the firebase reference
// Retrieve the post and listen for changes
databaseHandle = ref?.child("Posts3").observe(.value, with: { (snapshot) in
postData2.removeAll()
postData3.removeAll()
tableDataArray.removeAll()
for child in snapshot.children {
let snap = child as! DataSnapshot
let key = snap.key
let value = String(describing: snap.value!)
let rating = (value as NSString).integerValue
postData2.append(key)
postData3.append(value)
tableDataArray.append(tableData(boothName: key, boothRating: rating))
}
postData2.removeAll()
postData3.removeAll()
let sortedTableData = tableDataArray.sorted(by: { $0.boothRating > $1.boothRating })
for data in sortedTableData {
postData2.append(data.boothName)
let value = String(describing: data.boothRating)
postData3.append(value)
}
self.tableView.reloadData()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return postData2.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.font = UIFont.init(name: "Helvetica", size: 23)
cell.textLabel?.text = postData2[indexPath.row]
cell.detailTextLabel?.text = postData3[indexPath.row] + " ♥"
cell.detailTextLabel?.textColor = UIColor.red;
cell.detailTextLabel?.font = UIFont.init(name: "Helvetica", size: 23)
// cell.backgroundColor = UIColor.red;
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
return 80
}
}
class tableData {
var boothName: String
var boothRating: Int
init(boothName: String, boothRating: Int) {
self.boothName = boothName
self.boothRating = boothRating
}
}
A simple way is to have an conditional check to see if the indexPath.row value is within the last five.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
if(indexPath.row >= postData2.count-5){
cell.backgroundColor = UIColor.red
}else{
cell.backgroundColor = UIColor.white /* Remaining cells */
}
return cell
}
Some of the other answers will work - but it is nicer to use cells that have a known configuration when they are dequeued by cellForRowAt, not deal with a bunch of possible starting conditions each time you dequeue a cell. To do this subclass the UITableViewCell and override prepareForReuse(). This function will be called just before a cell is returned by dequeueReusableCell. Then cells can be set to a known starting point before you configure them. If cells could be received configured any possible way in cellForRowAt, you soon wind up with a very long function with a lot of if/else conditions.
The condition
if indexPath.row >= postData2.count - 5 {
cell.backgroundColor = UIColor.red
}
can be used as it is, and prepareForReuse takes care of the cells not keeping any settings when they are recycled. Here's an example:
override func prepareForReuse() {
super.prepareForReuse()
backgroundColor = UIColor.white
}
With this one simple setting it's a wash whether you do the if/else approach or use subclassing to make the most of prepareForReuse. But as soon as you have more than one thing to set in a cell you will find it is far less complex to use this function and results in far fewer mistakes with the appearance of cells - consider what would happen if there were more than one possible color a cell could be, or there were multiple elements in the cell to be configured with multiple possible values...
You can add simple logic
if indexPath.row >=(postData2.count-5) {
cell.backgroundColor = UIColor.red
}else {
cell.backgroundColor = UIColor.white
}
Just check a condition for setting the red colour for last five rows.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
if(indexPath.row >= postData2.count-5){
cell.backgroundColor = UIColor.red;
}else {
cell.backgroundColor = UIColor.white; //white colour for other rows
}
return cell
}
This method is recommended by the system, this method is more circumventing reuse in some cases (like when you modify the contents of a control in the cell surface)
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "cell")
// Not the type of cell, if the queue will return nil, at this time requires create ⼀ cell
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
}
}
If it involves data processing, you can create a new NSMutableSet(), Used to store your operations (ordinary data is lost, stored in the didSelecetRow inside indexPath like) save anyway, a unique tag.
These are just solve the problem of multiplexing, to deal with discoloration, refer to the above solution.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
if(indexPath.row >= postData2.count-5){
cell.backgroundColor = UIColor.red
}else{
cell.backgroundColor = UIColor.white /* Remaining cells */
}
return cell
}
I'm new to swift and working on a project in Swift 3.0 where I have a UITableView with three custom cells. In the first one I just have a image,button and a label. In the second one I have an image plus a label along with expandable and collapsible headers.Thus I have three different sections for this second cell. And lastly the third one is also contains just a label. In the first cell the UILabel is set underneath the image which contains a description about a person (constraints are been set). My requirement is only for the first cell dynamically adjust the cell size based on the size of the description. Help would much appreciate, the code as bellow.
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
print("Number of Sections: \(section)")
return arrayForTableView[section]
}
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let headerView : UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
headerView.contentView.backgroundColor = UIColor.yellow.withAlphaComponent(1.0)
}
func tapped(sender: UITapGestureRecognizer)
{
if let tag = sender.view?.tag{
expanedSections[tag] = !expanedSections[tag]
}
tableView.reloadData()
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UITableViewHeaderFooterView()
headerView.tag = section
let tapRecog = UITapGestureRecognizer(target: self, action: #selector(tapped))
tapRecog.numberOfTapsRequired = 1
tapRecog.numberOfTouchesRequired = 1
tapRecog.delegate = self
headerView.addGestureRecognizer(tapRecog)
return headerView
}
func numberOfSections(in tableView: UITableView) -> Int {
return arrayForTableView.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return 1
case 1:
return expanedSections[section] ? getItemsForSection(self.tableData.freeGifts): 0
case 2:
return expanedSections[section] ? getItemsForSection(self.tableData.exclusiveOffers) : 0
case 3:
return expanedSections[section] ? getItemsForSection(self.tableData.allAudios) : 0
case 4:
return expanedSections[section] ? getItemsForSection(self.tableData.testamonials) : 0
default:
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// var cell: UITableViewCell?
print("Section : \(indexPath.section) : \(indexPath.row)")
switch indexPath.section {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "HealerDetailsCell", for: indexPath) as! HealerDetailsTableViewCell
//cell.aboutLabel.preferredMaxLayoutWidth = (tableView.bounds)
cell.aboutLabel.sizeToFit()
populateHealerDetails.populateTable(cell, self.tableData.healerDetails)
return cell
case 1:
if tableData.freeGifts.count > 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "OffersCell",for: indexPath)
PopulateHealerDetailsAndOffers.populateTable(cell, self.tableData.freeGifts[indexPath.row] as! NSDictionary)
return cell
} else {
let cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
cell.textLabel?.text = "No Free Gifts At This Time"
return cell
}
case 2:
if tableData.exclusiveOffers.count > 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "OffersCell",for: indexPath)
PopulateHealerDetailsAndOffers.populateTable(cell, self.tableData.exclusiveOffers[indexPath.row] as! NSDictionary)
return cell
}else {
let cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
cell.textLabel?.text = "No Exclusive Offers At This Time"
return cell
}
case 3:
if tableData.allAudios.count > 0{
let cell = tableView.dequeueReusableCell(withIdentifier: "OffersCell",for: indexPath)
PopulateHealerDetailsAndOffers.populateTable(cell, self.tableData.allAudios[indexPath.row] as! NSDictionary)
return cell
}else{
let cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
cell.textLabel?.text = "NO Audios To Display"
return cell
}
case 4:
if tableData.testamonials.count > 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "TestamonialsCell", for: indexPath)
return cell
}else{
let cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
cell.textLabel?.text = "No Testamonials"
return cell
}
default:
let cell = tableView.dequeueReusableCell(withIdentifier: "TestamonialsCell", for: indexPath)
return cell
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//let indexPath = tableView.indexPathForSelectedRow!
//let currentCellValue = tableView.cellForRow(at: indexPath)! as UITableViewCell
}
1.Set the constraint of label.
2.Put numberOflines is equal to 0(Through storyboard or programmatically)
Add this code in viewDidLoad:
tableView.estimatedRowHeight = 300
tableView.rowHeight = UITableViewAutomaticDimension
Use this delegate method
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
For version >= iOS 8
override func viewDidLoad()
{
self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 44.0; // set to whatever your "average" cell height is
}
Steps to set constraints on storyboard:here
Important
If multiple lines labels, don't forget set the numberOfLines to 0.
Don't forget label.preferredMaxLayoutWidth =
CGRectGetWidth(tableView.bounds)
I think you want to expand/elapse UITableViewCell depending on the data each cell would have at runtime. I suppose, you already have implemented all of the first aid options regarding UITableView in swift.
Please try this method, which will always be called when your each cell is loaded.
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
//CellAnimator.animateCell(cell: cell, withTransform: CellAnimator.TransformWave, andDuration: 1)
//This commented line possibly might not be your requirement.
//But this is actually used to animate cell while loading.
//You can try some constraints or cell height related stuff here which would definitely work for each cell differently.
//Try calling cell specific loads either.
tableView.scrollToRow(at: indexPath as IndexPath, at: .none, animated: true)
/*let indexPath = IndexPath(item: (selectedCellIndexPath?.row)!, section: 0)
tableView.reloadRows(at: [indexPath], with: .none)
checkTrue = true
*/
}
Please check out this:
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
var tableViewDataSource = ["fewhf wfh wf wfw h dfw \n\n wufhw f ewfw wf w \n\n f wefe wfef w","fewhf wfh wf wfw h dfw \n\n wufhw f ewfw wf w \n\n f wefe wfef w",
"fewhf wfh wf wfw h dfw \n\n wufhw f ewfw wf w \n\n f wefe wfef w",
"fewhf wfh wf wfw h dfw \n\n wufhw f ewfw wf w \n\n f wefe wfef w"
]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableView.delegate = self
tableView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Tableview
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableViewDataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellHere") as! TableViewCellHere
cell.cellHere.text = tableViewDataSource[indexPath.row]
cell.cellHere.textAlignment = .justified
return cell
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == 0 || indexPath.row == 1
{
return 120.0
}
else
{
return 50.0
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == 0 || indexPath.row == 1
{
return 120.0
}
else
{
return 50.0
}
}
}
This is working for me like this:
enter image description here
I have a UITableView.It has two custom prototype cells.Now one cell is fixed it will be just remain one in tableview but another cell will be added to tableview again & again on button click.
below is code for the tableview methods:
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arr_fields.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cellIndentifier="property"
let cell:CreatePropertyCell=tableView.dequeueReusableCell(withIdentifier: cellIndentifier, for: indexPath) as! CreatePropertyCell
cell.layer.borderWidth = 2.0
cell.layer.borderColor = UIColor.gray.cgColor
cell.txt_propertyName.attributedPlaceholder = NSAttributedString(string:"Name of property",
attributes:[NSForegroundColorAttributeName: UIColor.gray])
return cell
} else {
let cellIdentifier = "attribute"
let cell:AddProperty=tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! AddProperty
cell.layer.borderWidth = 2.0
cell.layer.borderColor = UIColor.gray.cgColor
cell.txt_AddProperty.attributedPlaceholder = NSAttributedString(string:"Property Attribute",
attributes:[NSForegroundColorAttributeName: UIColor.gray])
cell.btnAdd.tag=indexPath.row
return cell
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 15
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = UIView()
header.backgroundColor = UIColor.clear
return header
}
#IBAction func actionAddProperty(_ sender: AnyObject) {
let cellIdentifier = "attribute"
let cell:AddProperty = self.tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! AddProperty
cell.layer.borderWidth = 2.0
cell.layer.borderColor = UIColor.gray.cgColor
cell.txt_AddProperty.attributedPlaceholder = NSAttributedString(string:"Property Attribute",
attributes:[NSForegroundColorAttributeName: UIColor.gray])
cell.tag=sender.tag!+1
arr_fields.append(cell)
tableView.reloadData()
print("tag is \(sender.tag!)")
}
Now i just want to add second cell to the table view not the both the cells.As of now it adds both the cells to the table view.
Try this:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 1
} else {
return arr_fields.count
}
}
Insert Cell: Rather than reloading Table, insert one cell into the Table:
#IBAction func actionAddProperty(_ sender: AnyObject) {
let cellIdentifier = "attribute"
let cell:AddProperty = self.tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! AddProperty
cell.layer.borderWidth = 2.0
cell.layer.borderColor = UIColor.gray.cgColor
cell.txt_AddProperty.attributedPlaceholder = NSAttributedString(string:"Property Attribute",
attributes:[NSForegroundColorAttributeName: UIColor.gray])
cell.tag=sender.tag!+1
let indexPath = NSIndexPath.init(forRow: arr_fields.count-1, inSection: 1)
tableView.beginUpdates()
arr_fields.append(objComment)
tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
tableView.endUpdates()
}