Reputation: 1336
I'm trying to create a tableView that has (for now) only a button in each cell.
I hard coded the number of rows to be 100:
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 100
}
And this is my cellForRowAt function that creates the button and is suppose to properly place it in each cell:
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell")
let row = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let btn = UIButton(type:(UIButtonType.custom)) as UIButton
btn.backgroundColor = UIColor.black
btn.setTitle("(read more)", for: UIControlState.normal)
btn.titleLabel!.font = UIFont(name: "Helvetica", size: 10)
btn.frame = CGRect(x:300, y:row.bounds.height, width:70, height:20)
btn.addTarget(self, action: Selector(("buttonPressed:")), for: UIControlEvents.touchUpInside)
btn.tag = indexPath.row
cell.contentView.addSubview(btn)
return cell
}
So this places the buttons in each cell, but when I click on the cell, the associated button disappears or when i scroll down, most of the first few buttons are gone when I scroll back up. What am I doing wrong here? Any help would be greatly appreciated!
Thanks in advance.
Upvotes: 2
Views: 663
Reputation: 5060
you must create a cell everytime in cellForRowAt
rather get the cell from dequeue and draw your content again. Creating a cell again and again is not an good idea. Finding own mistake and solving will another curve of learning.
l
et cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell") // should not do
let row = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) // can use it.
both line together should not use.
Upvotes: 0
Reputation: 866
This example maybe will help you:
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet fileprivate weak var tableView: UITableView!
fileprivate let numberOfItems = 100
override func viewDidLoad() {
super.viewDidLoad()
tableView.contentInset.top = 44
}
@objc fileprivate func buttonPressed(sender: UIButton) {
print("tag: \(sender.tag)")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numberOfItems
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let accessory = UIButton(frame: CGRect(x: 0, y: 0, width: 70, height: 20))
accessory.backgroundColor = .black
accessory.setTitle("Read more", for: .normal)
accessory.titleLabel?.font = UIFont(name: "Helvetica", size: 12)
accessory.tag = indexPath.row
accessory.addTarget(self, action: #selector(buttonPressed(sender:)), for: .touchUpInside)
cell.accessoryView = accessory
return cell
}
}
Upvotes: 2