Swift:字典键为CGRect

问题描述 投票:0回答:2

我需要将framebutton保存为关键,将index保存为阵列value。以下是代码:

var buttonLocationWithIndex = Dictionary<CGRect, Int>()

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    for (index, point) in enumerate(self.points){
        let pointButton = UIButton()
        pointButton.frame = point.bounds
        self.buttonLocationWithIndex[point.frame] = index
        self.view.addSubview(pointButton)
    }

我在尝试声明字典时遇到错误:Type 'CGRect' does not confirm to protocol 'Hashable'

UPDATE

func pressed(sender: UIButton!) {
    var alertView = UIAlertView();

    alertView.addButtonWithTitle("Ok");
    alertView.title = "title";
    var boundsIndex = self.buttonLocationWithIndex[sender.frame]
    var value = self.points(boundsIndex)
    alertView.message = value
    alertView.show();
}

错误:Cannot invoke points with an arguments list of type (Int?)'

swift nsdictionary
2个回答
3
投票

通过扩展在qazxsw poi上实施qazxsw poi协议。

Hashable

它将允许您使用CGRect作为关键。


0
投票

这是一个老问题,但由于我最近需要这个,我认为这对其他人有用。

在Swift 5中实现CGRect的Hashable协议的当前方法是:

extension CGRect: Hashable {
    public var hashValue: Int {
        return NSStringFromCGRect(self).hashValue
    }
}

资料来源:CGRect

© www.soinside.com 2019 - 2024. All rights reserved.