1

I created a floating button by this first answer. It works but when the UICollectionViewlaunched, the floating button still square and became circle after all datas appear (after loadAPI finished running).

Here's my code:

 override func viewDidLoad() {
    super.viewDidLoad()

    self.roundButton = UIButton(type: .custom)
    self.roundButton.setTitleColor(UIColor.orange, for: .normal)
    self.roundButton.addTarget(self, action: #selector(self.ButtonClick(_:)), for: UIControlEvents.touchUpInside)
    self.view.addSubview(self.roundButton)

    self.loadAPI(Page: 1)
}

override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()
    roundButton.layer.cornerRadius = roundButton.layer.frame.size.width/2
    roundButton.backgroundColor = green
    roundButton.clipsToBounds = true
    roundButton.setImage(UIImage(named:"ic_add_white_2x"), for: .normal)
    roundButton.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
        roundButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
        roundButton.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -20),
        roundButton.widthAnchor.constraint(equalToConstant: 60),
        roundButton.heightAnchor.constraint(equalToConstant: 60)
    ])
}

@IBAction func ButtonClick(_ sender: UIButton){
 //print("clicked")
}

I need the button being a circle since the UICollectionView first appears. Can somebody help me please? Thanks!

catcatcat
  • 377
  • 1
  • 5
  • 19
  • 1
    Since you do `roundButton.widthAnchor.constraint(equalToConstant: 60), roundButton.heightAnchor.constraint(equalToConstant: 60)`, you know that its widht/height will be 60. Then, just do `roundButton.layer.cornerRadius = 60.0/2` from the start at viewDidLoad and all the other infos like backgroundColor, etc, not in `viewWillLayoutSubviews()`. – Larme Mar 14 '18 at 10:02
  • @Larme wow that's perfect! Thank you! :) – catcatcat Mar 14 '18 at 10:27

1 Answers1

2

// update this code

override func viewDidLoad() {
    super.viewDidLoad()

    self.roundButton = UIButton(type: .custom)
    self.roundButton.setTitleColor(UIColor.orange, for: .normal)
    self.roundButton.layer.cornerRadius = roundButton.layer.frame.size.width/2
    self.roundButton.addTarget(self, action: #selector(self.ButtonClick(_:)), for: UIControlEvents.touchUpInside)
    self.view.addSubview(self.roundButton)

    self.loadAPI(Page: 1)
}
Ravi Padsala
  • 126
  • 2
  • 10