ios - 如何在按钮中绘制文本

标签 ios swift

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

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)

screenshot

关于ios - 如何在按钮中绘制文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51338633/

相关文章:

ios - TableView 中的多个 RowType - watchKit

ios - 强制用户使用自定义 init 方法进行初始化

ios - 尝试?传播而不是返回 nil

ios - 在当前 View Controller 具有 UITabBar 但没有 UITabBarController 时呈现 View Controller

ios - UIFont 等宽数字+小型大写字母

ios - UIcollection View 不滚动?

ios - 快速检测到碰撞时更改图像?

ios - AVAssetWriter - 设置自定义帧率

ios - 全景 View iOS

IOS 表情符号 unicode 列表