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

Adding UIButton to the center of a UITableViewCell using Swift

下面的代码只显示table最后一行的按钮。想知道为什么吗?

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
 }

而不是

button.center = self.view.center

尝试

let cellHeight: CGFloat = 44.0
button.center = CGPoint(x: view.bounds.width / 2.0, y: cellHeight / 2.0)

这假设您的 tableView 是全宽的,并且您的 cellHeight 是 44.0。您还不能从单元格本身获得实际高度。如果你想要实际高度,你必须从 tableView:willDisplayCell:forRowAtIndexPath: 方法或做其他事情。

此外,您应该在方法本身中使用 tableView 变量,而不是使用 self.myTable

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;   
}

如果有人正在寻找上述答案的 Swift 3 转换,试试这个:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: textCellIdentifier, for: indexPath)

    let button : UIButton = UIButton(type:UIButtonType.custom) as UIButton

    button.frame = CGRect(origin: CGPoint(x: 40,y :60), size: CGSize(width: 100, height: 24))
    let cellHeight: CGFloat = 44.0
    button.center = CGPoint(x: view.bounds.width / 2.0, y: cellHeight / 2.0)
    button.backgroundColor = UIColor.red
    button.addTarget(self, action: #selector(buttonClicked), for: UIControlEvents.touchUpInside)
    button.setTitle("Click Me !", for: UIControlState.normal)

    cell.addSubview(button)
    return cell
}

func buttonClicked(sender : UIButton!) {
    print("Clicked!")
}