Add Text Label and Button to dynamic tableview cell programmatically with Swift

后端 未结 2 2064
情深已故
情深已故 2021-02-06 10:08

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

2条回答
  •  失恋的感觉
    2021-02-06 10:54

    I got the solution for your question, please follow the below steps

    var data = ["iPad", "iPhone", "iWatch", "iPod", "iMac"]
    var buttonData = ["US","China","London","Canada","Japan"];
    
    
    //UITableViewDataSource Methods
    
     func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat 
     {
        return 80
     }
    
     func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
     {
        return data.count
     }
    
     func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
     {
    
        var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
    
        var label = UILabel(frame: CGRectMake(280.0, 14.0, 100.0, 30.0))
        label.text = data[indexPath.row]
        label.tag = indexPath.row
        cell.contentView.addSubview(label)
    
    
        let btn = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
        btn.backgroundColor = UIColor.greenColor()
        btn.setTitle(buttonData[indexPath.row], forState: UIControlState.Normal)
        btn.frame = CGRectMake(0, 5, 80, 40)
        btn.addTarget(self, action: "buttonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
        btn.tag = indexPath.row
        cell.contentView.addSubview(btn)
    
        return cell
     }
    
     //Button Action is
     func buttonPressed(sender:UIButton!)
     {
        let buttonRow = sender.tag
        println("button is Pressed")
        println("Clicked Button Row is",buttonRow)
     }
    

提交回复
热议问题