简体   繁体   English

Swift:在代码中但不在情节提要中包含UITableViewCell的同时在每个单元格中添加一个UIButton

[英]Swift: Adding a UIButton in each cell while having a UITableViewCell in the code but not in the storyboard

I have a list of tracks, which represents list of tasks stored in the array, anyways, I need to have a button next to each that is named "Track" So that the user can track to this task by moving to another page that has this functions. 我有一个跟踪列表,它表示存储在阵列中的任务列表,无论如何,我需要在每个跟踪列表旁边有一个名为“ Track”的按钮,以便用户可以通过移至另一个具有以下内容的页面来跟踪此任务这个功能。 My problem is that I couldn't make the button displayed next to each cell. 我的问题是我无法使按钮显示在每个单元格旁边。 the code of displaying the information in table view: 在表格视图中显示信息的代码:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")

    cell.textLabel?.text = trackMgr.tracks[indexPath.row].name

    cell.detailTextLabel?.text = String(trackMgr.tracks[indexPath.row].score)

    return cell



}

This is what my table view looks like in the storyboard: here 这是我的表格视图在情节提要中的样子: 这里

What I tried to do is declaring "mybutton" that equals UIButton! 我试图做的是声明等于UIButton的“ mybutton”! at the top, and then calling cell.mybutton.text = "text" but it didn't work. 在顶部,然后调用cell.mybutton.text =“ text”,但是它不起作用。

you can use following code for creating button on every cell and accordingly you can perform track task after pressing buttons. 您可以使用以下代码在每个单元格上创建按钮,因此可以在按下按钮后执行跟踪任务。

Have a look on following code 看下面的代码

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")

    cell.textLabel?.text = "hello"
    let track_Button = UIButton()
    track_Button.setTitle("Track", forState: .Normal)
    track_Button.setTitleColor(UIColor.blueColor(), forState: .Normal)
    track_Button.frame = CGRectMake(self.view.frame.size.width-100, 0, 100, 40)
    track_Button.backgroundColor = UIColor.grayColor()
    track_Button.addTarget(self, action: "track_Button_Pressed:", forControlEvents: .TouchUpInside)
    cell.addSubview(track_Button)

    return cell


}

func track_Button_Pressed(sender: UIButton!) {

    // Track Functionality
    println("Add Track Functionality here")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM