我不知道我在这里做错了什么。有谁知道这段代码有什么错误吗?
let text = "Hi" // text to be drawn
let uiText = NSAttributedString(string: text) //converting into NSAttributedString
let point = CGPoint(x: button.bounds.midX, y: button.bounds.midY) //where to draw
uiText.draw(at:point) // drawing hello in that point
button.backgroundColor = UIColor.red
最佳答案
你应该使用这个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)
关于ios - 如何在按钮中绘制文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51338633/