Reputation: 1089
I have a UIView
and a shadow around it. The problem is that the shadow looks good in the simulator but not on a real device. Both simulator and my iPhone have the iOS version.
My code: I use it inside a UITableViewCell
class.
override func awakeFromNib() {
super.awakeFromNib()
let shadowFrame: CGRect = cellView.layer.bounds
let shadowPath: CGPath = UIBezierPath(rect: shadowFrame).cgPath
cellView.layer.shadowOffset = CGSize(width: 0, height: 1)
cellView.layer.shadowColor = UIColor.gray.cgColor
cellView.layer.shadowRadius = 1
cellView.layer.shadowOpacity = 0.6
cellView.clipsToBounds = false
cellView.layer.shadowPath = shadowPath
}
EDIT The iPhone 7 simulator shows the same shadow as my iPhone 6. Only the iPhone 7plus Simulator can display the shadow right. Is that a Xcode bug?
Upvotes: 0
Views: 1271
Reputation: 15331
This code will work fine when the dimensions of the view are the same as your nib. However, awakeFromNib
is likely to be called before the autolayout engine has completed its layout passes, meaning cellView.layer.bounds
will not be set to the dimensions that rendered on screen. You should try moving the setting of your shadow path to layoutSubviews
in your UITableViewCell
subclass or cellForRowAtIndexPath
in your UITableViewDataSource
You can also try to just observe when your table view cell's frame is set and update the shadow path then.
class MyTableViewCell: UITableViewCell
{
var cellView: UIView?
override var frame: CGRect
{
didSet
{
guard let cellView = self.cellView, self.frame != oldValue else { return }
cellView.layer.shadowPath = UIBezierPath(rect: cellView.bounds).cgPath
}
}
}
Upvotes: 1