我需要将frame
的button
保存为关键,将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?)'
通过扩展在qazxsw poi上实施qazxsw poi协议。
Hashable
它将允许您使用CGRect
作为关键。
这是一个老问题,但由于我最近需要这个,我认为这对其他人有用。
在Swift 5中实现CGRect的Hashable协议的当前方法是:
extension CGRect: Hashable {
public var hashValue: Int {
return NSStringFromCGRect(self).hashValue
}
}
资料来源:CGRect