如何在Swift 3中为TableView的单元格添加阴影?

3
我想在具有4个部分(一个具有4个tableViewCell的tableView)的tableViewCell中添加阴影,其中最后一个单元格我想在3个侧面(左、右、下)添加阴影,但在除了最后一个单元格之外的其他单元格中,我只想在2个侧面(左、右)添加阴影。我在单例和UIView扩展中编写了此代码。 对于最后一个单元格:
 func dropShadowAtBottom() {

    self.layer.masksToBounds = false
    self.layer.shadowColor = UIColor.black.cgColor
    self.layer.shadowOpacity = 0.2
    self.layer.opacity = 0.3
    self.layer.shadowOffset = CGSize(width: 0, height: 2)
    self.layer.shadowRadius = 2
    self.clipsToBounds = false

}

除了最后一个单元格外,对于另一个单元格:

func dropShadowAtLeftAndRight() {

    self.layer.masksToBounds = false
    self.layer.shadowColor = UIColor.black.cgColor
    self.layer.shadowOpacity = 0.5
    self.layer.shadowOffset = CGSize(width: 0, height: 0)
    self.layer.shadowRadius = 2
    let shadowRect: CGRect = self.layer.bounds.insetBy(dx: 0, dy: 4);  // inset top/bottom
    self.layer.shadowPath = UIBezierPath(rect: shadowRect).cgPath

    self.layer.rasterizationScale = UIScreen.main.scale
    self.layer.shouldRasterize = true

}

我在 cellForRow 方法中调用了这段代码:

if(indexPath.row == currentOrderHistory.listOrderItems.count - 1){
            cell.bodyView.dropShadowAtBottomOnly()

        }else{
            cell.bodyView.dropShadowAtLeftAndRight()
        }
        return cell

目前这段代码可以工作但仍不完美。单元格之间有空白。

图片

我只想让它们连接在一起。


2
如果您发布您想要实现的图像,那将非常有帮助。 - Nicolas Miari
尝试分享您想要实现的内容。 - Nazmul Hasan
我已经添加了图片,请点击“图片”文本。 - Ferdinanzxcvbnm
2个回答

0

我认为你在这一行的dropShadowAtLeftAndRight()遇到了问题。

let shadowRect: CGRect = self.layer.bounds.insetBy(dx: 0, dy: 4); 

在我的情况下,它将返回像这样的rect(0.0, 4.0, 375.0, 36.0)。顶部有4px的空白,底部也有4px的空白。

因此,您的左侧和右侧阴影将从4开始,高度为36。

要解决此问题,您需要进行如下设置:

let shadowRect: CGRect = self.layer.bounds.insetBy(dx: 0, dy: 0);

1
如果我把dy改成0,那么所有的单元格都会有底部阴影。 - Ferdinanzxcvbnm
你可以只使用 "dropShadowAtBottom" 方法,并在单元格的左侧和右侧添加两个视图,以提供左侧和右侧的阴影。 - jignesh Vadadoriya

0

你尝试过从IB中删除分隔符吗?

enter image description here

分隔符设置为

或者另一种方式,将分隔符颜色设置为半透明

self.tableView.separatorColor = UIColor.clear

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接