4

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

这就是它在 iphone 5s 版本 11 中的样子

这就是它在 iphoneX 版本 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 或设置状态栏的情况下做到这一点。

4

1 回答 1

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)
于 2017-12-20T10:55:46.863 回答