Recently, I started with a Card view added as a subview of UIView in a view-controller. When a view controller created along subviews, it tends to use entire screen bounds and also slips behind Tab bar or Navigation bar. In my current situation, it's second case. Casually new iOS developers will write a patch by additional value for coordinate y and subtracting bar height from its size. A lot of them posted in SO threads too :
- How to prevent UINavigationBar from covering top of view?
- View got hidden below UINavigationBar iOS 7
- Navigation Bar covers some part of view at Top
So, how I got solved ?
self.edgesForExtendedLayout = []
This will avoid all subviews in a view controller get behind any bars. Read full apple documentation on here.
Full Source code below :
Bonus Tips :
For subviews inherited from ScrollView (UITableView, UICollectionView etc) make sure set True for automaticallyAdjustsScrollViewInsets property as well.
Also, note `insetBy` API a smart way to get margin from all sides instead of using CGRect initialiser.
Full Source code below :
//Simple view controller where its view layed-out as a card.
class WidgetCardViewController : UIViewController {
var containerView = UIView()
//MARK:- View Controller Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .lightGray
containerView.backgroundColor = .white
self.view.addSubview(containerView)
edgesForExtendedLayout = [] //To avoid navigation bar cover the Card.
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
containerView.cornerRadius = 10.0
containerView.frame = self.view.bounds.insetBy(dx: 10.0, dy: 10.0)
}
}//MARK:- View Extension to create corner radius.
extension UIView {
@IBInspectable
var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
}
}
}Bonus Tips :
For subviews inherited from ScrollView (UITableView, UICollectionView etc) make sure set True for automaticallyAdjustsScrollViewInsets property as well.
Also, note `insetBy` API a smart way to get margin from all sides instead of using CGRect initialiser.