Home > Software design >  How to show a UIButton of UITableView's Section Header above UINavigationBar?
How to show a UIButton of UITableView's Section Header above UINavigationBar?

Time:08-01

I am using UIKit SDK for building the app. I have added a button as a UITableView header for section. I want it to stick to the top of UINavigationBar while scrolling. It does stick to the top but the button goes beneath the navigation bar. I want the button to be visible above the navigation bar. I tried setting the layer.zPosition value of navigation bar to -1 but it hides the entire navigation bar.

Here's my code for the button and the tableview section header:

lazy var playButton: UIButton = {
        let pButton = UIButton(type: .roundedRect)
        pButton.backgroundColor = UIColor(named: GlobalConstants.darkGreenColor)!
        pButton.tintColor = .white
        pButton.setImage(playIcon, for: .normal)
        pButton.layer.cornerRadius = 40
        pButton.enableAutoLayout()
        pButton.clipsToBounds = false
        return pButton
    }()

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat
{
return 1
}

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
let headerView = UIView()
headerView.backgroundColor = .clear
headerView.addSubview(playButton)
NSLayoutConstraint.activate([
playButton.widthAnchor.constraint(equalToConstant: 80),
playButton.heightAnchor.constraint(equalToConstant: 80),
playButton.trailingAnchor.constraint(equalTo: headerView.trailingAnchor, constant: -20),
playButton.centerYAnchor.constraint(equalTo: headerView.topAnchor)
])
return headerView
}

How do I solve this ?

screenshot of app

CodePudding user response:

Add your button further up in the view hierarchy, probably in the window directly:

UIApplication.shared.windows.first(where: { $0.isKeyWindow })?.addSubview(floatingButton)

Then in your viewController override scrollViewDidScroll and set the y position of your floatingButton

  • Related