视图中的所有UITextField [英] All UITextField in a View
问题描述
在viewDidLoad中,我将使用下面的代码扫描所有UITextField和set addTarget。我有3个UITextField但只找到其中的一个。
In viewDidLoad I would scan all UITextField and a set addTarget with the code below. I have 3 UITextField but only 1 of that is found.
for subview in self.view.subviews
{
println(subview)
if (subview.isKindOfClass(UITextField))
{
var textField = subview as UITextField
textField.addTarget(self, action: "textFieldDidReturn:", forControlEvents: UIControlEvents.EditingDidEndOnExit)
textField.addTarget(self, action: "textFieldDidBeginEditing:", forControlEvents: UIControlEvents.EditingDidBegin)
}
}
视图非常简单,专为锻炼而设计。 1个UIimageView,3个UITextField,1个按钮,1个标签。但println(子视图)只显示
The view is very simple, built for exercise. 1 UIimageView, 3 UITextField, 1 button, 1 label. But the println(subview) display only
<UITextField: 0x7a739cf0; frame = (57 430; 290 30); text = ''; clipsToBounds = YES; opaque = NO; autoresize = RM+BM; layer = <CALayer: 0x7a739c90>>
<UIImageView: 0x7a742d70; frame = (0 0; 0 0); autoresize = RM+BM; userInteractionEnabled = NO; layer = <CALayer: 0x7a742ef0>>
<_UILayoutGuide: 0x7a7430d0; frame = (0 0; 0 0); hidden = YES; layer = <CALayer: 0x7a743270>>
<_UILayoutGuide: 0x7a743650; frame = (0 0; 0 0); hidden = YES; layer = <CALayer: 0x7a7436d0>>
找到并设置第一个UITextField,其他不是。为什么?我哪里错了?
The first UITextField is found and set, the others not. Why? Where am I wrong?
换句话说。扫描视图中所有对象的正确方法是什么?
In other word. What is the right way to scan all the objects in a view?
谢谢
推荐答案
问题仅在于您过早运行代码。您的代码位于视图控制器超类的 viewDidLoad
中。那时,它的视图已加载,但其子类的视图没有 - 并且子类的视图是所有子视图的位置。因此,您获取日志记录代码的结果虽然令人惊讶,但完全正确 - 代码运行时。
The problem is merely that you are running your code too soon. Your code is in your view controller superclass's viewDidLoad
. At that time, its view has loaded, but its subclass's view has not - and the subclass's view is where all the subviews are. So the result you are getting for your logging code, while surprising, is perfectly correct — at the moment that the code runs.
只需移动将您的日志代码转换为 viewDidAppear:
的实现,或者在接口完全就绪后调用的其他方法,您将获得结果你期待。我用你的项目测试了它,它工作正常。
Just move your logging code into an implementation of viewDidAppear:
or some other method that is called after the interface is completely ready, and you'll get the result you expect. I tested that with your project and it works fine.
这篇关于视图中的所有UITextField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!