我在应用程序的视图控制器中有一个表视图,并且单元格中的数据显示良好,但是我试图使该表适应于卡片视图。我编写了代码尝试将其添加到其中,但是单击该单元格并返回到该表后,该卡仅出现在表单元格中。此时,只有选定的单元格显示卡,而所有其他单元格保持不变。
我在原型单元格中添加了一个UIView并将其标记为我编写的名为“ CardView”的新类。该类的代码如下:
import UIKit
@IBDesignable
class CardView: UIView {
@IBInspectable var cornerRadius: CGFloat = 15
@IBInspectable var shadowColor: UIColor? = UIColor.black
@IBInspectable let shadowOffsetWidth: Int = 3
@IBInspectable let shadowOffsetHeight: Int = 3
@IBInspectable let shadowOpacity: Float = 0.2
override func layoutSubviews() {
layer.cornerRadius = cornerRadius
layer.shadowColor = shadowColor?.cgColor
layer.shadowOffset = CGSize(width: shadowOffsetWidth, height: shadowOffsetHeight)
let shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius)
layer.shadowPath = shadowPath.cgPath
layer.shadowOpacity = shadowOpacity
backgroundColor = UIColor.blue
}
}
如果这也可能影响我要完成的工作,请在表的视图控制器中使用cellForRowAt函数。我在这里所做的唯一修改就是将内容视图指定为白色,该视图应显示在卡片视图的周围:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//Table view cells are reused and should be dequeued using a cell identifier.
let cellIdentifier = "cell"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? AccountTableViewCell else {
fatalError("The dequeued cell is not an instance of AccountTableViewCell")
}
//Fetches the appropriate account for the data source layout.
let account = accounts[indexPath.row]
cell.accountName.text = account.name
cell.amountDue.text = String(format: "$%.2f", account.amountDue)
cell.contentView.backgroundColor = UIColor.white
return cell
}