【问题标题】:Swift 3 - Floating Button over UICollectionViewSwift 3 - UICollectionView 上的浮动按钮
【发布时间】:2018-03-14 09:44:41
【问题描述】:

我通过this first answer 创建了一个浮动按钮。它可以工作,但是当UICollectionViewlaunched 时,浮动按钮仍然是方形并在所有数据出现后变成圆形(在 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 首次出现以来,我需要将按钮设为一个圆圈。有人可以帮我吗?谢谢!

【问题讨论】:

  • 既然你做了roundButton.widthAnchor.constraint(equalToConstant: 60), roundButton.heightAnchor.constraint(equalToConstant: 60),你就知道它的宽度/高度将是60。然后,只需从viewDidLoad和所有其他信息(如背景颜色等)开始做roundButton.layer.cornerRadius = 60.0/2,而不是在viewWillLayoutSubviews().
  • @Larme 哇,太完美了!谢谢! :)

标签: swift uicollectionview uibutton floating-action-button


【解决方案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)
}

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 2017-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-19
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    相关资源
    最近更新 更多