Add Text Label and Button to dynamic tableview cell programmatically with Swift
39,078
You can implement like this
let titleArray = ["a", "b", "c"]
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 50
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//return no.of cell do you want
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cellHeight = tableView(self.tableView, heightForRowAtIndexPath: NSIndexPath(forRow: indexPath.row, inSection: indexPath.section))
var cell = CustomCell(frame: CGRectMake(0, 0, self.view.frame.width, cellHeight), title: titleArray[indexPath.row])
cell.cellLabel.text = //labelText
cell.cellButton.addTarget(self, action: "buttonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
return cell
}
class CustomCell: UITableViewCell {
var cellButton: UIButton!
var cellLabel: UILabel!
init(frame: CGRect, title: String) {
super.init(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")
cellLabel= UILabel(frame: CGRectMake(self.frame.width - 100, 10, 100.0, 40))
cellLabel.textColor = UIColor.blackColor()
cellLabel.font = //set font here
cellButton = UIButton(frame: CGRectMake(5, 5, 50, 30))
cellButton.setTitle(title, forState: UIControlState.Normal)
addSubview(cellLabel)
addSubview(cellButton)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
}
Author by
Don Draper
Updated on July 17, 2022Comments
-
Don Draper almost 2 years
I have a dynamic tableview and a prototype cell which displays an array. My questions is how would I add a button which displays different names on each cell to the Left side of the cell and then a label to the right side displaying the array info. Thanks! :D
So imagine this is the cell below:
Left side:Button(array info) <-------------------> Right side:TextLabel(array info)
-
Don Draper over 8 yearsIt says buttonWithType is unavailable, use object construction UIButton(type:)... Any suggestions?
-
Don Draper over 8 yearsSo, how do I have the labels and buttons conform to different size screens?
-
Farid Al Haddad almost 7 yearswhen the user will scroll, it will add the label and the button again and again and again ..
-
Anup Gupta over 6 years@FaridAlHaddad did you get any solution for this?