如何在 TableView 中居中自定义 UIView?

How to center a custom UIView in a TableView?

我正在尝试将自定义视图置于 UITableView 的中心,它工作正常,但是当我滚动时它不会更新到 tableview 的中心,它只是停留在顶部。这是我的代码:

 let customView = UIView(frame: CGRect(x: 0, y: 0, width: 150, height: 75))
    customView.backgroundColor = UIColor(red: 0/255, green: 174/255, blue: 250/255, alpha: 1.0)
    let label = UILabel(frame: CGRect(x: customView.frame.midX, y: customView.frame.midY, width: 150, height: 75))
    label.text = "Text"
    label.textAlignment = .center
    label.font = UIFont(name: "HelveticaNeue-Light", size: 18)
    label.textColor = UIColor.white
    customView.addSubview(label)
    label.center = customView.center
    customView.layer.cornerRadius = 4.0

    self.view.addSubview(customView)
    customView.center = CGPoint(x: self.tableView.bounds.width/2, y: self.tableView.bounds.height/2)

    UIView.animate(withDuration: 1.5, animations: {
        customView.alpha = 0.0
    }) { (success: Bool) in
        customView.removeFromSuperview()
    }

关于如何使这项工作有任何想法吗?谢谢

在 tableView 中添加 customView,而不是在视图中。

self.tableView.addSubview(customView)