gpt4 book ai didi

objective-c - NSSegmentedControl - 有没有办法将(id)representedObject附加到控件的每个NSSegmentedCell部分?

转载 作者:行者123 更新时间:2023-12-03 17:21:28 26 4
gpt4 key购买 nike

有一个NSSegmentedControl,我尝试将不同的representedObject附加到每个NSSegmentedCell。我认为我可能做错了一些事情,因为它似乎不起作用。

[mySegmentedControl setSelectedSegmented:0];
[mySegmentedControl selectedCell] setRepresentedObject:myObject0];

[mySegmentedControl setSelectedSegmented:1];
[mySegmentedControl selectedCell] setRepresentedObject:myObject1];

然后我认为这会很简单:

[mySegmentedControl setSelectedSegment:0];
myObjectType *type = (myObjectType *)[[mySegmentedControl selectedCell] representedObject];

似乎不起作用?我做错了什么吗?我的问题似乎是:

[[mySegmentedControl selectedCell] representedObject] 

似乎总是我附加的最新对象。因此,如果我选择段 0,它将返回我为段 1 附加的所表示的对象。有什么想法吗?

最佳答案

selectedCell is inherited from NSControl 。来自文档:

The default implementation of this method simply returns the control's associated cell (or nil if no cell has been set). Subclasses of NSControl that manage multiple cells (such as NSMatrix and NSForm) must override this method to return the cell selected by the user.

但是,NSSegmentedControl 不管理多个单元,它是 just one cell为整体控制。这就是为什么它的行为与您想象的不同(对于 NSSegmentedControl,它始终返回控件的单元格,因此 mySegmentedControl.selectedCell == mySegmentedControl.cell )。

因此,当您调用 [[mySegmentedControl selectedCell] setRepresentedObject:myObject1]; 时,您将覆盖之前设置的表示对象,因为您始终获得相同的单元格实例。

解决这个问题的一种方法是使用 NS(Mutable)ArrayNS(Mutable)Dictionary (带有索引的 NSNumber作为键,如 myDict[@(index)]) 中存储“表示的”对象。然后,您可以将此数组或字典指定为分段单元格的表示对象:

mySegmentedControl.cell.representedObject = representedArrayOrDict;

关于objective-c - NSSegmentedControl - 有没有办法将(id)representedObject附加到控件的每个NSSegmentedCell部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25366710/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com