2014-12-15 Shadows and rounded corners

The app I'm currently working on, requires a textfield with shadow and rounded corners. That doesn't work on a UITextField; you'll have to make it transparent, then add it to a plain UIView and style that.

I got curious and tried to add shadows and rounded corners to a number of elements in UIKit. This is the code:

        import UIKit
	class ViewController: UIViewController {
		
		@IBOutlet weak var contentView: UIView!
		@IBOutlet weak var button: UIButton!
		@IBOutlet weak var textfield: UITextField!
		@IBOutlet weak var textView: UITextView!
		@IBOutlet weak var datePicker: UIDatePicker!
		@IBOutlet weak var toolbar: UIToolbar!
		@IBOutlet weak var imageView: UIImageView!
		override func viewDidLoad() {
			super.viewDidLoad()
			self.addShadowAndCornerRadius(self.contentView)
			self.addShadowAndCornerRadius(self.textfield)
			self.addShadowAndCornerRadius(self.button)
			self.addShadowAndCornerRadius(self.textView)
			self.addShadowAndCornerRadius(self.datePicker)
			self.addShadowAndCornerRadius(self.toolbar)
			self.addShadowAndCornerRadius(self.imageView)
			
		}
		
		func addShadowAndCornerRadius(view: UIView) {
			let radius:CGFloat = 20.0
			view.layer.cornerRadius = radius
			view.layer.shadowColor = UIColor.darkGrayColor().CGColor
			view.layer.shadowPath = UIBezierPath(roundedRect: view.bounds,
			    cornerRadius: radius).CGPath
			view.layer.shadowOffset = CGSize(width: 0, height: 0)
			view.layer.shadowOpacity = 1.0
			view.layer.masksToBounds = true
			view.clipsToBounds = false
		}
	}

Below is the result in the simulator. Note that the light-blue empty element is a plain UIView.

shadow and rounded corners uikit.png

As you can see, adding shadow and rounded corners doesn't work on UIImageView, UITextField and UIToolbar. It does work on a plain UIView, UIButton, UITextView and UIDatePicker.