uitableview - 使用 Swift 将 UIButton 添加到 UITableViewCell 的中心

标签 uitableview swift

以下代码仅显示表格最后一行中的按钮。有什么想法吗?

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    var cell:UITableViewCell = self.myTable.dequeueReusableCellWithIdentifier("cell") as UITableViewCell

    let button : UIButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
    button.frame = CGRectMake(40, 60, 100, 24)
    button.center = self.view.center
    button.backgroundColor = UIColor.redColor()
    button.addTarget(self, action: "buttonClicked:", forControlEvents:
    UIControlEvents.TouchUpInside)
    button.setTitle("Click Me !", forState: UIControlState.Normal)
    cell.addSubview(button
 }
 return cell
 }

最佳答案

Jawwad 的建议解决了这个问题。这里的文档是整个工作功能:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {              

        var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell  

        let button : UIButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
        button.frame = CGRectMake(40, 60, 100, 24)
        let cellHeight: CGFloat = 44.0
        button.center = CGPoint(x: view.bounds.width / 2.0, y: cellHeight / 2.0)
        button.backgroundColor = UIColor.redColor()
        button.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
        button.setTitle("Click Me !", forState: UIControlState.Normal)

        cell.addSubview(button)

        return cell;   
}

关于uitableview - 使用 Swift 将 UIButton 添加到 UITableViewCell 的中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27967338/

相关文章:

swift - 增加底部布局的长度/插图/填充

macos - 为什么我的 Split View会这样,我该如何解决?

ios - Tableview 不重新加载数据

ios - 如何在下面给出的 Hidekeyboard 函数中包含多个 UITextField?

ios - 在每个单元格都包含表格 View 的表格 View 中选择新单元格时,无法取消选择先前选择的单元格

IOS TableView multi 按部分选择

objective-c - 以编程方式访问 AWS IAM 用户策略和访问权限

ios - 接受数组的 Swift 函数给出错误 : '@lvalue $T24' is not identical to 'CGFloat'

iOS 15 - UItableView 顶部填充问题

ios - 如何使用 UITableView 在列表内创建列表