【问题标题】:Swift 5 Circle Button (Programmatically)Swift 5 圆形按钮(以编程方式)
【发布时间】:2019-11-22 00:57:54
【问题描述】:

我正在尝试以编程方式编写一个圆形按钮,但它总是以正方形结束。我已经尝试了几件事,到处看了看,但不知道还能做什么。 代码的第二部分在另一个类中。

static let warriorButton: UIButton = {

    let button = UIButton(type: .system)
    button.backgroundColor = .blue
    button.setTitle("WARRIOR", for: .normal)
    button.translatesAutoresizingMaskIntoConstraints = true
    button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
    button.isEnabled = true

    return button
}()



warriorButton.anchor(top: view.topAnchor, left: view.leftAnchor, bottom: nil, right: nil, paddingTop: 100, paddingLeft: 60, paddingBottom: 0, paddingRight: 0, width: 90, height: 90)
warriorButton.layer.cornerRadius = warriorButton.layer.bounds.size.width/2;
warriorButton.clipsToBounds = true;

【问题讨论】:

  • 尝试添加warriorButton.layer.masksToBounds = true,你可能需要warriorButton.isOpaque = true
  • 显示func anchor(top: ...代码
  • 在warriorButton.layer.cornerRadius之前添加warriorButton.layoutIfNeeded()

标签: swift xcode11 swift5 programmatically


【解决方案1】:

在viewDidLayoutSubviews 之前使用按钮宽度还为时过早,所以要么

warriorButton.layer.cornerRadius = 45
warriorButton.clipsToBounds = true

或在里面

override func viewDidLayoutSubviews() {
   super.viewDidLayoutSubviews()
    warriorButton.layer.cornerRadius = warriorButton.frame.size.width/2     
    warriorButton.clipsToBounds = true
}

【讨论】:

    【解决方案2】:

    将此行添加到您的代码中

    warriorButton.clipsToBounds = true
    warriorButton.layer.cornerRadius = warriorButton.frame.size.width / 2
    

    【讨论】:

      【解决方案3】:

      只需将此行添加到您的代码中

      yourButton.layer.cornerRadius = yourButton.frame.height/2
      

      【讨论】:

        【解决方案4】:

        2021 答案:

        Button(action: {}) {
            Text("WARRIOR")
        }.foregroundColor(Color.white)
        .padding(30)
        .background(
            Circle()
            .fill(Color.blue)
        )
        

        【讨论】:

          猜你喜欢
          • 2021-01-31
          • 1970-01-01
          • 2021-10-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-09-28
          • 2020-12-31
          相关资源
          最近更新 更多