Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SWIFT UITableViewCell with corner radius and shadow

Tags:

ios

swift

swift3

I've been trying to create a custom tableview cell with rounded corners and drop shadow, I managed to create the rounded corners but the shadow is showing only on the corners and no where else.

like image 451
user6679849 Avatar asked Feb 25 '17 12:02

user6679849


People also ask

How do I set the corner radius of a UIView?

Implementing the @IBDesignable UIView extension and applying the @IBInspectable modifier to the cornerRadius property allows a view’s corner radius to be set in a Storyboard’s Attributes Inspector: Adding a shadow to a UIView can be implemented by setting the shadowColor, shadowOpacity, shadowOffset, and shadowRadius properties on the view’s layer:

What is @ibinspectable attribute in UIView?

This inspectable attribute can be applied to other properties of UIView that are missing from Interface Builder. Let’s add a borderColor property. Since the @IBInspectable attribute builds upon the mechanism for user-defined runtime attributes, we are still limited to the types that can be set by Xcode’s Interface Builder.

How do I add a shadow to a UIView?

Adding a shadow to a UIView can be implemented by setting the shadowColor, shadowOpacity, shadowOffset, and shadowRadius properties on the view’s layer: An @IBDesignable UIView extension marking the shadow properties as @IBInspectable can be implemented to allow view shadows to be configured in a Storyboard:

What is the @ibinspectable attribute in Xcode?

Since the @IBInspectable attribute builds upon the mechanism for user-defined runtime attributes, we are still limited to the types that can be set by Xcode’s Interface Builder. We have to perform some trickery if the types do not line up exactly with the property we want to set.


1 Answers

For both the shadow and the rounded corners, you can use this code:

 override func tableView(_ tableView: UICollectionView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

     let cell = tableView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
     cell.layer.cornerRadius = 10
     let shadowPath2 = UIBezierPath(rect: cell.bounds)
     cell.layer.masksToBounds = false
     cell.layer.shadowColor = UIColor.black.cgColor
     cell.layer.shadowOffset = CGSize(width: CGFloat(1.0), height: CGFloat(3.0))
     cell.layer.shadowOpacity = 0.5
     cell.layer.shadowPath = shadowPath2.cgPath
     return cell
 }

And you can adjust the values and you'll get the perfect shadow for you!

Hope it helps!

like image 189
Mr. Xcoder Avatar answered Oct 29 '22 18:10

Mr. Xcoder