我正在将蒙版应用于自定义表格单元格中的图像。面罩工作正常,但一旦我滚动表格,面罩上就会出现
Fatal error: Unexpectedly found nil while unwrapping an Optional value
UIImageView
。
这是我的代码(为了简洁起见,我省略了一些变量声明):
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LeagueTableCell") as UITableViewCell?
let badgeFgr = cell?.viewWithTag(9) as! UIImageView
let badgeMask = cell?.viewWithTag(4) as! UIImageView
// Set the image
if let theImage = UIImage(named: imageString) {
badgeFgr.image = theImage.withRenderingMode(.alwaysTemplate)
badgeFgr.tintColor = fgrCol
// Apply the mask
badgeMask.image = UIImage(named: "maskShape")
badgeFgr.mask = badgeMask
}
return cell!
}
当我滚动表格时,应用程序崩溃,并且此行出现
Fatal error: Unexpectedly found nil while unwrapping an Optional value
:
let badgeMask = cell?.viewWithTag(4) as! UIImageView
当我显示图像不应用遮罩(通过删除下面的行)时,它会显示没有遮罩的图像,并且滚动时不会崩溃:
// Apply the mask
theMask.image = UIImage(named: "maskShape")
theImage.mask = theMask
那么将蒙版应用于自定义表格视图单元格中的图像的正确方法是什么?
您收到错误的原因是因为这一行:
badgeFgr.mask = badgeMask
删除该图像视图。
不要尝试在单元原型中使用预先添加的图像视图,而是像这样应用蒙版:
// Apply the mask
if let maskImg = UIImage(named: "maskShape") {
// create a NEW image view to use as the mask
let imgV = UIImageView(frame: badgeFgr.bounds)
imgV.image = maskImg
badgeFgr.mask = imgV
}