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

时间:2020-05-11 07:02:46

标签: ios swift uikit

我有一个带有自定义单元格的UITableView,每节间隔一个单元格。我想添加图片作为单元格背景,但是我不确定该怎么做。如果我设置单元格背景图片,则它会被containerView遮盖,并且没有弯角。有什么建议?我正在使用iPad上的Playgrounds,因此我希望通过编程方式进行。这是我到目前为止的内容:

导入UIKit 导入PlaygroundSupport

ViewController类: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)
}

}

扩展ViewController {

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()

1 个答案:

答案 0 :(得分:0)

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

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