Swift 3 - UICollectionView上的浮动按钮

时间:2018-03-14 09:44:41

标签: swift uicollectionview floating-action-button

我在this first answer创建了一个浮动按钮。它可以工作但是当UICollectionView启动时,浮动按钮仍然是正方形,并且在所有数据出现后变为圆形(在loadAPI完成运行之后)。

这是我的代码:

 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")
}

自首次出现UICollectionView以来,我需要按钮为圆形。有人可以帮帮我吗?谢谢!

1 个答案:

答案 0 :(得分:1)

//更新此代码

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)
}