在swift中使用Label中的标题初始化一个按钮

时间:2017-01-25 13:11:25

标签: ios swift uibutton uilabel programmatically-created

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

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)

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

提前致谢

3 个答案:

答案 0 :(得分:2)

您可以将自定义标签作为子视图添加到您的按钮,就像像这样的评论中提到的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
    }
}

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

enter image description here

答案 1 :(得分:0)

您的标签有text属性。您使用它来设置值,您也可以使用它来获取值。文本是可选的,因此您需要解包。

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

答案 2 :(得分:0)

if let textFromLabel = yourCustomLabel.text {

    yourButton.setTitle(textFromLabel, .normal)
}

是我建议你做的事情