【问题标题】:Initialize a button with a title from a Label in swift用 swift 中的标签初始化一个带有标题的按钮
【发布时间】:2017-01-25 13:11:25
【问题描述】:

我想从标签初始化按钮的标题。我有这个代码:

let smallSquare = CGSize(width: 30, height: 30)
let button = UIButton(frame: CGRect(origin: CGPointZero, size: smallSquare))

但是,我不知道如何用我的标签初始化标题:

let label = UILabel(frame: CGRectMake(0, 0, 200, 21))
label.center = CGPointMake(160, 284)
label.textAlignment = NSTextAlignment.Center
label.text = "I'am a test label"

通常,我使用这个属性来添加一个带有字符串的标题:

button.setTitle("Button Title",for: .normal)

是否可以简单地将我的标签放在按钮的标题中?

提前致谢

【问题讨论】:

  • 你可以addSubView标签到按钮
  • 已经在 UIButton 视图中给出了 titleLable。使用它。
  • 你试过button.setTitle(label.text!,for: .normal)吗?

标签: ios swift uibutton uilabel programmatically-created


【解决方案1】:

您可以像这样在 cmets 中提到的 Mike Alter 将自定义标签作为子视图添加到按钮中(注意:代码在 Swift 3 中,但应该很容易被 Swift 2.* 采用。提示在代码 cmets 中):

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white

        let smallSquare = CGSize(width: 30, height: 30)
        let button = UIButton(frame: CGRect(origin: .zero, size: smallSquare))
        button.translatesAutoresizingMaskIntoConstraints = false
        button.backgroundColor = .red

        // add the button to your view
        view.addSubview(button)

        // set constraints of your button
        button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true


        let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
        label.translatesAutoresizingMaskIntoConstraints = false
        label.center = CGPoint(x: 160, y: 284)
        label.textAlignment = .center
        label.text = "I'm a test label"

        // add the label to your button
        button.addSubview(label)

        // set constraints of your label
        label.centerXAnchor.constraint(equalTo: button.centerXAnchor).isActive = true
        label.centerYAnchor.constraint(equalTo: button.centerYAnchor).isActive = true
    }
}

自定义值的结果如下所示(刚刚添加了按钮的红色背景,以便您看到按钮的框架与标签框架相比):

【讨论】:

    【解决方案2】:

    您的标签具有text 属性。你用它来设置一个值,你也可以用它来获取这个值。文本是可选的,因此您需要展开。

    let labelText = label.text ?? ""
    button.setTitle(labelText, for: .normal)
    

    【讨论】:

      【解决方案3】:
      if let textFromLabel = yourCustomLabel.text {
      
          yourButton.setTitle(textFromLabel, .normal)
      }
      

      我会建议你这样做

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-12
        • 1970-01-01
        • 1970-01-01
        • 2011-01-13
        • 2017-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多