仅在iOS 11中设置顶部安全区域的背景颜色

时间:2017-11-13 08:16:40

标签: ios iphone swift3 safearealayoutguide

我是Swift的新手。我已经以编程方式设置了我的顶栏。除了iOS版本11之外,它适用于所有版本。

this is how it looks in iphone 5s version 11

This is how it looks in iphoneX version 11

我想更改iPhone X中安全区域的背景颜色。目前我刚刚添加了以下代码来隐藏状态栏。

 override var prefersStatusBarHidden: Bool {
    return true
}

我使用代码创建了顶栏:

//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;
    //ImageView - Back Button
    let backBtn = UIButton(frame:CGRect(x: 25, y: 18, width: 18, height: 34))
    let backBtnImage = UIImage(named: "back_button") as UIImage?
    backBtn.setImage(backBtnImage, for: .normal)
    backBtn.layer.masksToBounds = true
    backBtn.addTarget(self,action:#selector(backButtonClicked),
                      for:.touchUpInside)
    //Label - Title
    let titleLabel = UILabel(frame:CGRect(x: width * 0.3, y: 13, width: width * 0.55, height: 40))
    titleLabel.text = "Favorites"
    titleLabel.contentMode = UIViewContentMode.center
    //include all in view
    topBar.addSubview(titleLabel)
    topBar.addSubview(backBtn)

    containerView.addSubview(topBar)

有没有办法可以在不使用UINavigationBar或设置状态栏的情况下完成。

1 个答案:

答案 0 :(得分:0)

您好,你也可以尝试这个, 需要添加在标题视图中设置的具有相同背景的视图,并添加到容器父视图。 请参考以下代码

//Top Bar


    let safeAreaView = UIView(frame:CGrect(x: 0,y: 0, width: width, height: 40))
    safeAreaView.backgroundColor = UIColor.white
    self.view.addSubview(safeAreaView)

    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;
    //ImageView - Back Button
    let backBtn = UIButton(frame:CGRect(x: 25, y: 18, width: 18, height: 34))
    let backBtnImage = UIImage(named: "back_button") as UIImage?
    backBtn.setImage(backBtnImage, for: .normal)
    backBtn.layer.masksToBounds = true
    backBtn.addTarget(self,action:#selector(backButtonClicked),
                      for:.touchUpInside)
    //Label - Title
    let titleLabel = UILabel(frame:CGRect(x: width * 0.3, y: 13, width: width * 0.55, height: 40))
    titleLabel.text = "Favorites"
    titleLabel.contentMode = UIViewContentMode.center
    //include all in view
    topBar.addSubview(titleLabel)
    topBar.addSubview(backBtn)

    containerView.addSubview(topBar)