Kishor Pahalwani
Kishor Pahalwani

Reputation: 1022

How can we add a button over collection view using swift?

I have a UICollectionViewController in my main.storyboard.
I want to add a circle button to redirect to new page, But in storyboard is it possible to drag a button over UICollectionView? I don't know about footer how can we achieve.

It should looks like UICollectionView is scrolling and button will be over the collection view, I mean no effect on button.

Upvotes: 1

Views: 7072

Answers (2)

Zaid Pathan
Zaid Pathan

Reputation: 16820

Yes you can do it,

If using UIViewController Put your button above collectionview like this,

enter image description here

If using UICollectionViewContoller, you can't add button to storyboard, you need to add button programmatically. Call below function in viewDidLoad().

fileprivate func addButton(){
    let button = UIButton()
    button.translatesAutoresizingMaskIntoConstraints = false
    button.setTitle("Button", for: UIControlState.normal)
    button.setTitleColor(UIColor.black, for: UIControlState.normal)
    self.view.addSubview(button)
    button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
    button.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
    button.widthAnchor.constraint(equalToConstant: 100).isActive = true
    button.heightAnchor.constraint(equalToConstant: 50).isActive = true
}

Upvotes: 4

UfoXp
UfoXp

Reputation: 619

Are you using a UICollectionViewController? You have to switch to UIViewController implementing UICollectionViewDataSource and UICollectionViewDelegate. Then you place UICollectionView there and UIButton over it so there will be "root" UIView and those two views underneath it. Connect all required outlets and actions and you are done.

Upvotes: 4

Related Questions