[英]How to draw a text in a button
我不知道我在做什么错。 有谁知道此代码中的错误是什么。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.