我是iPhone开发者中的新手。我的应用程序根据我的数据模型动态创建按钮。这个模型不仅仅是一个简单的列表;它是一棵树。我需要某种方法将一个已创建的按钮与该数据模型关联起来,这样当单击该按钮时,我就知道它对应于模型的哪个部分。
在Windows上,大多数UI控件都有一个“标记”字段,您可以在其中放置自定义数据。使用类似的模式,我想在iPhone上做的是:
- (void)createMyButton:(MyModel*)foo { UIButton* button = <insert creation code here> [button addTarget:self action:@selector(handleCreatedButtonTouch:) ...]; button.tag = foo; } - (void)handleCreatedButtonTouch:(id)sender { UIButton* button = (UIButton*)sender; MyModel* foo = (MyModel*)(button.tag); [foo userTouchedMyButton]; }
我在苹果的文档中找不到关于这个领域的任何提及。你的iPhone专家是怎么做到的?同样,我没有任何简单的方法来索引到我的数据模型中,并且对整个数据模型进行枚举以查找匹配项似乎是非常错误的。
安德鲁,
iPhone SDK中的UI元素具有 tag 与您描述的内容类似的属性。如果你想使用button.tag,那么你可以直接使用。
tag
对伪代码的唯一更改是 handleCreatedButtonTouch: 方法。线:
handleCreatedButtonTouch:
MyModel* foo = (MyModel *)(button.tag);
会尝试铸造 标签 属性到 MyModel 对象。您可能希望在MyModel中创建一个初始值设定项来处理查找,例如:
标签
MyModel
MyModel *foo = [[MyModel alloc] initFromButtonWithTag:[sender tag]];
希望这有帮助。