我正在尝试使用 NSAttributedString 更新按钮标题字段。所以我尝试设置属性标题,但它不能正常工作。它没有显示我放入 NSAttributedString 的正确属性属性。我得出的结论是,要么我的初始化 NSAttributedString 的方法不正确,要么按钮覆盖了颜色。
我得到了字符串的原始值,但没有属性属性。
卡片结构
struct Card {
private var shape : Shape = Shape.none
private var color : Color = Color.none
private var number : Number = Number.none
private var shading : Shading = Shading.none
//These attributes are not showing up
private var strokeTextAttributes : [NSAttributedStringKey:Any] = [NSAttributedStringKey:Any]()
private var manipulatedValue : String = ""
init(shape : Shape, color : Color, number : Number, shading : Shading){
self.shape = shape
self.color = color
self.number = number
self.shading = shading
//How many multiples of the shape should be on the card
for _ in 1...number.rawValue{
manipulatedValue.append(shape.rawValue)
}
//0 is the NSStringKey, 1 is the UIColor
strokeTextAttributes[color.rawValue.0] = color.rawValue.1
}
func rawValue() -> NSAttributedString{
return NSAttributedString(string: manipulatedValue, attributes: strokeTextAttributes)
}
}
视图控制器类
class ViewController: UIViewController {
private var game : Set = Set()
override func viewDidLoad() {
super.viewDidLoad()
for index in 0...game.cardsInPlay.count-1{
cardButtons[index].layer.borderWidth = 3.0
cardButtons[index].layer.borderColor = UIColor.black.cgColor
cardButtons[index].layer.cornerRadius = 8.0
cardButtons[index].setAttributedTitle(game.cardsInPlay[index]!.rawValue(), for: UIControlState.normal)
}
}
@IBOutlet var cardButtons: [UIButton]!
}
我尝试将这些值硬编码到 Card 结构的初始化程序中。但同样的情况会再次发生。该按钮显示卡片和数字的正确形状,但不是正确的颜色。颜色将是 Main.Storyboard 检查器中的默认颜色。浅蓝。问题是字典无法正常工作,因此 strokeTextAttributes 不包含任何有意义的内容,或者 UIButton 正在做一些愚蠢的事情。