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

标签 swift button dynamic tableview cell

我有一个动态 TableView 和一个显示数组的原型(prototype)单元格。我的问题是如何在单元格的左侧添加一个在每个单元格上显示不同名称的按钮,然后在右侧显示数组信息的标签。谢谢! :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)
    }
}

关于swift - 使用 Swift 以编程方式将文本标签和按钮添加到动态 tableview 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33053398/

相关文章:

swift - 为什么我不能在通知中传递带有枚举键的字典

objective-c - 尝试将 Swift 与 Obj C header 用于 Coda2 插件。获取错误 : Undefined symbols for architecture x86_64

ios - Swift 2 - REST 服务和由搜索栏过滤的 TableView

没有填充的 Android 按钮

.net - 为什么每个不同的动态调用都会导致两个异常,并且可以抑制这些异常?

VB.NET:如何动态选择 ListView 项?

ios - 核心数据栈结构

BlackBerry:带有图像的按钮,用于正常、聚焦和按下状态

html - 悬停淡入淡出按钮下的文本

android - 如何正确地动态更新 Spinner?