使用 swift 中标签的标题初始化按钮

Initialize a button with a title from a Label in swift

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

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)

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

提前致谢

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

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

    yourButton.setTitle(textFromLabel, .normal)
}

我建议你这样做

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

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

使用您的自定义值的结果如下所示(只需添加按钮的红色背景,这样您就可以看到按钮的框架与标签框架的对比):