使用 Swift 以编程方式将文本标签和按钮添加到动态表格视图单元格

2024-03-01

我有一个动态表格视图和一个显示数组的原型单元格。我的问题是如何在单元格左侧添加一个在每个单元格上显示不同名称的按钮,然后在右侧添加一个显示数组信息的标签。谢谢! :D

想象一下这是下面的单元格:

左侧:Button(数组信息) 右侧:TextLabel(数组信息)


你可以这样实现

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)
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Swift 以编程方式将文本标签和按钮添加到动态表格视图单元格 的相关文章

随机推荐