如何在按钮中绘制文本

时间:2018-07-14 12:46:13

标签: ios swift

我不知道我在做什么错。有谁知道这段代码有什么错误。

.css

1 个答案:

答案 0 :(得分:0)

您应该使用此UIButton的方法

button.setAttributedTitle(uiText, for: .normal)

这是代码(我创建了两个带有虚拟属性的虚拟按钮)

    let text = "Hi"

    let attributesFirst = [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 17), NSAttributedStringKey.foregroundColor: UIColor.lightGray,
                           NSAttributedStringKey.strokeColor: UIColor.orange]
    let attributesSecond = [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedStringKey.foregroundColor: UIColor.red,
                            NSAttributedStringKey.strokeColor: UIColor.blue]


    let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
    button.backgroundColor = .red
    button.center = view.center

    let button2 = UIButton(frame: button.frame)
    button2.backgroundColor = .orange
    button2.center = CGPoint(x: button.center.x, y: button.center.y + 200)

    let uiText = NSAttributedString(string: text, attributes: attributesFirst)
    let uitext2 = NSAttributedString(string: text, attributes: attributesSecond)

    button.setAttributedTitle(uiText, for: .normal)
    view.addSubview(button)

    button2.setAttributedTitle(uitext2, for: .normal)
    view.addSubview(button2)

screenshot