简体   繁体   中英

How to add shadow to a view inside cell in tableview in ios?

I have created a tableviewcell in XIB and used it in tableview using registering the class. I am using autolayout here.

But the problem is when i loading the tableview in viewcontroller the shadow of the view inside the cell is not setting correctly. it exceeds its bounds as i shown in picture with red box. 在此处输入图片说明

But when is scrolling the tableview then the shadow of the view is shown correctly as expected.

The code used in cellForRowAtIndexPath is shown below:

let layer = cell.cellContectView.layer
        layer.shadowOffset = CGSizeMake(1.0, 1.0)
        layer.shadowColor = UIColor.blackColor().CGColor
        layer.shadowRadius = 5
        layer.shadowOpacity = 0.2
        layer.masksToBounds = false
        layer.shadowPath = UIBezierPath(rect: layer.bounds).CGPath

Please note: the blurred text is not an issue. Its hidden for security reason

You can try to remove the code for the layer from the cellForRowAtIndexPath and put it in your cell class in:

override func prepareForReuse() {
    let layer = self.contentView.layer
    layer.shadowOffset = CGSizeZero
    layer.shadowColor = UIColor.blackColor().CGColor
    layer.shadowRadius = 5
    layer.shadowOpacity = 0.2
    layer.masksToBounds = false
    layer.shadowPath = UIBezierPath(rect: layer.bounds).CGPath
}

Adding a shadow inside UITableViewCell using QuartzCore code - can decrease scroll performance dramatically.
Better to create shadow graphic asset and add it as UIImageView .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM