Проблемы с NSAttributedString и Button

Я пытаюсь обновить поле заголовка кнопки с помощью 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)
    }
}

ViewController Класс

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 делает что-то глупое.


person nwar1994    schedule 08.07.2018    source источник
comment
UIButton следует за свойством tintColor, если этот тип кнопки является системным. Попробуйте изменить тип кнопки на индивидуальный?   -  person Chunlei Wang    schedule 08.07.2018
comment
Хм ... просто сделал его черным без эффекта нажатия кнопки   -  person nwar1994    schedule 08.07.2018
comment
В вашем вопросе много недостающей информации. Какие фактические атрибуты применяются к атрибутированной строке? Добавьте print("attributes: \(strokeTextAttributes)") в свою Card.rawValue функцию, а затем обновите свой вопрос, указав точный результат пары отпечатков.   -  person rmaddy    schedule 08.07.2018
comment
атрибуты: [__C.NSAttributedStringKey (_rawValue: NSStrokeColor): UIExtendedSRGBColorSpace 1 0 0 1] атрибуты: [__C.NSAttributedStringKey (_rawValue: NSStrokeColor): UIExtendedSRGBColorSpace 0   -  person nwar1994    schedule 08.07.2018
comment
Я почти уверен, что с моей кнопкой button.setAttributedTitle что-то не так ... Я жестко закодировал атрибуты, используя [.strokeColor: UIColor.orange] ... Все равно не сработало. Это должно означать, что с кнопкой что-то происходит.   -  person nwar1994    schedule 08.07.2018
comment
Вы установили strokeColor, но не установили strokeWidth.   -  person Larme    schedule 08.07.2018
comment
@ nwar1994 Как я уже сказал, обновите свой вопрос. Публикация деталей в комментариях - неправильное место. Детали относятся к вашему вопросу, где люди их легче увидят.   -  person rmaddy    schedule 08.07.2018


Ответы (1)


Вы устанавливаете NSAttributedStringKey.strokeColor, но не устанавливаете NSAttributedStringKey.strokeWidth. Вот почему вы не получаете желаемого результата.
Если его нет, я предполагаю (и это имеет смысл) то же самое при установке .strokeWidth на 0, что указано в документации «ничего не делать»:

Укажите 0 (по умолчанию), чтобы никаких дополнительных изменений не происходило.

Я получил тот же результат, установив его на 0 или не установив его вообще.

Пример тестового кода:

let str = "Hello !"
let attributedString = NSMutableAttributedString.init(string: str,
                                                      attributes: [.font: UIFont.systemFont(ofSize: 40),
                                                                   .foregroundColor: UIColor.white])

let label1 = UILabel(frame: CGRect(x: 30, y: 40, width: 200, height: 50))
label1.backgroundColor = .lightGray
label1.attributedText = attributedString

let label2 = UILabel(frame: CGRect(x: 30, y: 95, width: 200, height: 50))
label2.backgroundColor = .lightGray
label2.attributedText = attributedString


let label3 = UILabel(frame: CGRect(x: 30, y: 150, width: 200, height: 50))
label3.backgroundColor = .lightGray
label3.attributedText = attributedString

let label4 = UILabel(frame: CGRect(x: 30, y: 205, width: 200, height: 50))
label4.backgroundColor = .lightGray
label4.attributedText = attributedString

attributedString.addAttributes([NSAttributedStringKey.strokeColor: UIColor.red],
                               range: NSRange.init(location: 0, length: attributedString.string.utf16.count))
label2.attributedText = attributedString
print("Only Stroke Color:\n\(attributedString)")

attributedString.addAttributes([NSAttributedStringKey.strokeWidth: 0],
                               range: NSRange.init(location: 0, length: attributedString.string.utf16.count))
label3.attributedText = attributedString
print("Stroke Color + Width set to 0:\n\(attributedString)")

attributedString.addAttributes([NSAttributedStringKey.strokeWidth: -4],
                               range: NSRange.init(location: 0, length: attributedString.string.utf16.count))
label4.attributedText = attributedString
print("Stroke Color + Width set to -4:\n\(attributedString)")

self.view.addSubview(label1)
self.view.addSubview(label2)
self.view.addSubview(label3)
self.view.addSubview(label4)

Вывод журнала:

$>Only Stroke Color:
Hello !{
    NSColor = "UIExtendedGrayColorSpace 1 1";
    NSFont = "<UICTFont: 0x7f8973e11120> font-family: \".SFUIDisplay\"; font-weight: normal; font-style: normal; font-size: 40.00pt";
    NSStrokeColor = "UIExtendedSRGBColorSpace 1 0 0 1";
}
$>Stroke Color + Width set to 0:
Hello !{
    NSColor = "UIExtendedGrayColorSpace 1 1";
    NSFont = "<UICTFont: 0x7f8973e11120> font-family: \".SFUIDisplay\"; font-weight: normal; font-style: normal; font-size: 40.00pt";
    NSStrokeColor = "UIExtendedSRGBColorSpace 1 0 0 1";
    NSStrokeWidth = 0;
}
$>Stroke Color + Width set to -4:
Hello !{
    NSColor = "UIExtendedGrayColorSpace 1 1";
    NSFont = "<UICTFont: 0x7f8973e11120> font-family: \".SFUIDisplay\"; font-weight: normal; font-style: normal; font-size: 40.00pt";
    NSStrokeColor = "UIExtendedSRGBColorSpace 1 0 0 1";
    NSStrokeWidth = "-4";
}

Рендеринг:

введите здесь описание изображения

person Larme    schedule 08.07.2018
comment
Братан, ты легенда ... Я уже 2 дня чешу затылок, лол! Могу я спросить, как вы это узнали из журналов? - person nwar1994; 08.07.2018
comment
Я знаком с NSAttributedString. Некоторым из них требуется две настройки. Когда вы знаете, насколько вы можете изменить настройки, кажется нормальным иметь возможность установить ширину для штриха, а в вашем журнале не было, только цвет. Также логика аналогична с myView.layer.borderColor и myView.layer.borderWidth. - person Larme; 08.07.2018