将UIView放在导航栏前面时看不到按钮

时间:2019-06-22 08:12:27

标签: ios swift uiview uinavigationcontroller

我有一个带有按钮的UIView,我使用UIView在按钮周围添加了一个圆形边框,该按钮可以正常工作并且定位完美,并且我希望UIView位于导航栏的前面,但是一旦添加UIView在导航栏的前面,该按钮消失了,但UIVew在导航栏的前面。

let viewBar = UIView()

let userProfileView = UIView()
let userProfileButton = UIButton(type: .custom)

override func viewDidLoad() {
    super.viewDidLoad()

    view.backgroundColor = .red
    setupNextButton()
    setupViewBar()
    setupUserProfileButton()
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    // To Bring the viewBar in front of the navigation bar        
    self.navigationController?.view.addSubview(viewBar)
}

func setupViewBar() {

    viewBar.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.5)

    view.addSubview(viewBar)
    addNavigationBarConstraints()
}

func setupUserProfileButton() {

    userProfileButton.setImage(#imageLiteral(resourceName: "profilePictureSmall.png"), for: .normal)
    userProfileButton.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
    userProfileButton.addTarget(self, action: #selector(profilePictureTapped), for: .touchUpInside)

    userProfileView.layer.cornerRadius = 20
    userProfileView.layer.borderWidth = 1.5
    userProfileView.clipsToBounds = true
    userProfileView.layer.borderColor = UIColor.black.cgColor

    userProfileView.addSubview(userProfileButton)

    //viewBar.addSubview(userProfileView)
    view.addSubview(userProfileView)
    addUserProfileButtonConstraints()

}

这是用户个人资料按钮和viewBar的约束

func addViewBarConstraints() {

    viewBar.translatesAutoresizingMaskIntoConstraints = false
    viewBar.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    viewBar.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    viewBar.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    viewBar.heightAnchor.constraint(equalToConstant: 100).isActive = true

}

func addUserProfileButtonConstraints() {

    userProfileView.translatesAutoresizingMaskIntoConstraints = false
    userProfileView.topAnchor.constraint(equalTo: viewBar.safeAreaLayoutGuide.topAnchor, constant: 5).isActive = true
    userProfileView.trailingAnchor.constraint(equalTo: viewBar.safeAreaLayoutGuide.trailingAnchor, constant: -15).isActive = true
    userProfileView.widthAnchor.constraint(equalToConstant: 40).isActive = true
    userProfileView.heightAnchor.constraint(equalToConstant: 40).isActive = true

}

如何使按钮出现?我也添加了一些图片。

UIView without navigation bar

UIView with (In front of) navigation bar

1 个答案:

答案 0 :(得分:0)

导航栏位于视图堆栈的顶部,因此它隐藏了红色的UIView。因此,从本质上讲,您必须将按钮添加到导航栏中,而不是将其添加到UIView:

    let barButton = UIBarButtonItem(customView: userProfileButton)
    self.navigationItem.rightBarButtonItem = barButton