[UIButton copyWithZone:]: 无法识别的选择器发送到实例

[UIButton copyWithZone:]: unrecognized selector sent to instance

    func createRowOfButtons(buttonTitles: [NSString]) -> UIView {
    var buttons = [UIButton]()
    let keyboardRowView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 50))
    var dict = [UIButton:String]()
    for buttonTitle in buttonTitles 
    {
       let button = createButtonWithTitle(title: buttonTitle as String)
        buttons.append(button)
        keyboardRowView.addSubview(button)
        dict.updateValue("\(buttonTitle)", forKey: button)
    }
    allButtons = NSMutableDictionary(dictionary: dict)
    //error:[UIButton copyWithZone:]: unrecognized selector sent to instance 0x7e011bc0
    addIndividualButtonConstraints(buttons: buttons, mainView:keyboardRowView)
    return keyboardRowView
}

我是 iOS 的新手,我想创建 UIButtonNSMutableDictionary,但出现以下错误:

Cannot cast 'UIButton' to 'NSCopying'.

我不明白为什么会出现这个错误。

提前致谢。

UIButton 不符合 NSCopying protocol 因此您不能将其用作 NSDictionary

中的键

来自 Apple 文档:

The key is copied (using copyWithZone:; keys must conform to the NSCopying protocol).

参考:This Question

的 pheelicks 回答

确实不确定为什么您必须使用 NSStringNSMutableArray,特别是考虑到您将 NSString 桥接到 String,这提示 NSString 实际上没用。

本地 buttonsdict 数组似乎也没有必要,因为在循环完成后,您只需将这些按钮分配给 allButtons。这意味着您可以直接寻址该存储(使用正确的 Swift [String: UIButton] 类型而不是 NSMutableDictionary):

var allButtons: [String: UIButton]!

func createRowOfButtons(buttonTitles: [String]) -> UIView {

    let keyboardRowView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 50))

    // Initialize / reset dictionary
    // Do it here or on declaration
    allButtons = [String: UIButton]()

    // Populate dictionary
    buttonTitles.forEach { title in
        let button = UIButton()// createButtonWithTitle(title: title)
        keyboardRowView.addSubview(button)
        allButtons[title] = button
    }

    addIndividualButtonConstraints(buttons: Array(allButtons.values),
                                   mainView: keyboardRowView)
    return keyboardRowView
}

您还可以通过标题访问按钮,反之亦然。