在 iPhone 中使用块设置委托
在视图控制器上,我有多个文本字段,它们都使用相同的委托。现在,在委托中,代码变得非常难看,因为我必须区分所有文本字段(一堆 if/else-if 或 switch 语句)。我遇到了这篇文章:
但由此我还是不明白这是如何解决问题的?这不是基本上调用一个方法并向其传递文本,并且该方法不知道哪个文本字段提供了字符串吗?您仍然需要区分文本字段,但这次是在块内(使用通常的 if(textfield == bazTextField)...)。
On a view controller I have multiple textfields, which all use the same delegate. Now in the delegate the code gets really ugly since I have to differentiate between all the textfields (bunch of if/else-if or a switch statement). I came a cross this article:
But from this I still don't understand how this solves the problem? Doesn't this basically call one method and pass it the text and the method has no idea what textfield gave the string? You would still need to differentiate between the textfields, but this time inside the block (with the usual if(textfield == bazTextField)...).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不知道它是否完全解决了问题,而是将其转移(并转移到 viewDidLoad 中,无论如何,它通常都会有一些混乱)。
然而,在该示例中,块本身被传递到文本字段中以与所有实例变量的值进行比较并“记住”所有实例变量的值(如果它引用它们),因此这就是它如何知道文本和文本字段是什么处理。
我不明白该代码究竟应该如何提供帮助,因为它将一个块分配给单个委托类以与所有文本字段委托一起使用 - 除非您可能应该为每个文本字段分配一个块,每个文本字段都有不同的堵塞。那么你的代码比使用 if 语句的代码多得多!
I don't know that it exactly solves the problem so much as shifts it (and into viewDidLoad, which usually gets a bit of mush-mash in it anyway).
However in that example the block itself was being passed in the textfield to run comparisons with and "remembers" the values of all the instance variables as well (if it refers to them), so that's how it knows what text and text field is being dealt with.
I don't see how that code exactly is supposed to help though, since it assigns one block to the single delegate class to be used with all text field delegates - unless perhaps you were supposed to have one per text field, each with a different block. Then you have way more code than you'd have had with the if statements!
这篇文章没有说清楚,但我相信这个想法是为您希望响应 textFieldShouldReturn 的每个 UITextField 创建这些块之一(和块委托对象)。
The article doesn't make it clear, but I believe the idea is to create one of these blocks (and block delegate objects) for each UITextField that you wish to have respond to textFieldShouldReturn.
嗯,也许我没有完全理解这篇文章,但我没有看到在该具体示例中使用块而不是选择器的优势。
您可以实现类似的效果
,但视图控制器
并不真正知道这是否比链接
if-else
更好。在我看来,这比它解决的问题更让事情变得复杂。
hm, maybe I didn't completely understand the article, but I don't see the advantage of using blocks instead of selectors in that concrete example.
you could achieve something similar like this
and the view controller
don't really know if that's any better than chaining
if-else
s though.it seems to me that this complicates things more than the problem it solves.