Geethanjali Reddy
Geethanjali Reddy

Reputation: 223

top bar overlapping in unsafe area

my top bar works fine in all other iPhones except iPhoneX due to safe area introduction.The top bar starts in unsafe area itself.The top bar is a custom UI.It looks as below:

This is how it looks in iPhone5s

This is how it looks in iPhoneX

The code is as follows:

    //Top Bar
    let topBar = UIView(frame:CGRect(x: 0,y: 0, width: width, height: 60))
    topBar.backgroundColor = UIColor.white
    topBar.layer.shadowColor = UIColor.gray.cgColor
    topBar.layer.shadowOffset = CGSize(width: 0, height: 3)
    topBar.layer.shadowOpacity = 1
    topBar.layer.masksToBounds = false
    topBar.layer.shadowRadius = 8.0;

    self.view.addSubview(topBar)

How do I fix this.I want view to start from safe area.And I don't want to use UINavigationBar.Thanks.

Upvotes: 0

Views: 664

Answers (2)

matt
matt

Reputation: 536046

And I don't want to use UINavigationBar

It doesn't matter what you want. You need to anyway. You have violated the interface guidelines and now you're in trouble because of it. Do what Apple wants you to do. UINavigationBar has the ability to stretch automatically up behind the "notch" when it is configured correctly. The same for UIToolbar at the bottom. You need to use these.

Upvotes: 0

Lumialxk
Lumialxk

Reputation: 6379

Use Auto-Layout and layout guide to build your UI. For example, use SnapKit.

let topBar = UIView(frame:CGRect(x: 0,y: 0, width: width, height: 60))
topBar.snp.makeConstraints { make in

    make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top)

    make.leading.trailing.equalToSuperview()
}

Update

Re-write with original api.

let topBar = UIView(frame:CGRect(x: 0,y: 0, width: 30, height: 60))
self.view.addSubview(topBar)
let top = NSLayoutConstraint.init(item: topBar, attribute: .top, relatedBy: .equal, toItem: self.view.safeAreaLayoutGuide, attribute: .top, multiplier: 1.0, constant: 0.0)
let leading = NSLayoutConstraint.init(item: topBar, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1.0, constant: 0.0)
let trailing = NSLayoutConstraint.init(item: topBar, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1.0, constant: 0.0)
let height = NSLayoutConstraint.init(item: topBar, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 50.0)
topBar.addConstraints([top, leading, trailing, height])

Upvotes: 1

Related Questions