将图像设置为UITableView单元格的背景



我有一个带有自定义单元格的UITableView,每个部分一个单元格用于间距。我想添加一个图像作为单元格背景,但我不确定该怎么做。如果我设置单元格背景图像,它会被容器视图遮挡,并且没有弯曲的角。有什么建议吗?我正在iPad上使用Playgrounds,所以我想以编程方式执行此操作。这是我到目前为止所拥有的:

导入 UIKit 导入游乐场支持

类视图控制器: UITableViewController {

override func viewDidLoad() {
super.viewDidLoad()
tableView.register(CardCell.self, forCellReuseIdentifier: "CardCell")
tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
tableView.contentInset = UIEdgeInsets(top: 0, left: 30, bottom: 0, right: -30)
tableView.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
}

}

扩展视图控制器 {

override func numberOfSections(in tableView: UITableView) -> Int {
return(5)
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.contentView.layer.masksToBounds = true
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section : Int) -> Int{
tableView.rowHeight = 200
// There is one row in each section
return 1
}
// Setup spacing between sections
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50
}
// Make headers transparent (fill with UIView, set as transparent)
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView()
headerView.backgroundColor = UIColor.clear
return headerView
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "CardCell", for: indexPath) as! CardCell
return cell
}

}

类 CardCell: UITableViewCell {

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)

layer.masksToBounds = false
layer.shadowOpacity = 0.23
layer.shadowRadius = 12
layer.shadowOffset = CGSize(width: 0, height: 0)
layer.shadowColor = UIColor.black.cgColor
layer.cornerRadius = 6
contentView.backgroundColor = .white
contentView.layer.cornerRadius = 8
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

}

PlaygroundPage.current.liveView = ViewController((

您可以像这样设置任何单元格的背景图像:

cell.selectedBackgroundView = UIImageView(image: UIImage(named: "cellBgImage.png")?.stretchableImage(withLeftCapWidth: Int(0.0), topCapHeight: Int(5.0)))

最新更新