1

我有一个UIView(MyView) 的子类,其中有一些UITextField子视图。MyView 实现了该UITextFieldDelegate协议,以便在单击文本字段时得到通知。这运作良好。现在我需要将文本字段放在一种“容器”中,以便能够通过UIView动画淡入和淡出这个容器(及其所有子项)。所以我创建了一个 UIView (MySubview),使它成为 MyView 的子视图,并将所有文本字段放在其中。动画效果很好,但UITextFieldDelegate不再被调用。我认为这是因为文本字段不再是 MyView 的直接子项。有没有其他方法可以解决这个问题?

更新

我做了一个小版本的代码,也许这有助于找到问题:

@interface MyView : UIView <UITextFieldDelegate>


@implementation MyView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        // This is MySubview:
        UIView *tempLabelsContainer = [[UIView alloc] initWithFrame:self.bounds];
        [tempLabelsContainer setUserInteractionEnabled:YES];
        [self addSubview:tempLabelsContainer];
        self.labelsContainer = tempLabelsContainer;
        [tempLabelsContainer release];

        UITextField *aTextField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 100, 20)];
        [aTextField setBackgroundColor:[UIColor clearColor]];
        [aTextField setText:@"Some text"];
        [aTextField setTag:1];
        [aTextField setDelegate:self];
        [self.labelsContainer addSubview:aTextField];
        [aTextField release];

        // More labels are being added
    }

    return self;
}

#pragma mark - UITextFieldDelegate methods

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    // This is not being called
    NSLog(@"TextField with the tag: %d should be edited", [textField tag]);    

    return NO;
}
4

2 回答 2

4

好吧,我试着写出你的代码,它对我有用。以下是您可以尝试更改的一些项目;

  • 您无法编辑 textField 的原因是您将 NO 返回到 textFieldShouldBeginEditing 方法。将此更改为“是”。
  • 尝试将您的 textField 定位(如果可能)略低于您给出的位置。此外,无论如何 20 像素对于正确的文本字段来说太小了,至少 40 像素。如果状态栏在手机中打开,则位于 0,0 的 20px 文本字段可能会完全隐藏。
  • 为您的文本字段设置一个边框样式。据我所知,这对于 textField 的显示和交互非常重要。(例如 textField.borderStyle = UITextBorderStyleRoundRect)

手指交叉!:)

于 2011-09-07T15:06:48.140 回答
0

我会回答我自己的问题,以防万一有人碰巧遇到同样的问题——很难想象有人会犯这样愚蠢的错误,不过:

我将标签容器的框架设置为 self.bounds。但是 MyViewController 正在创建带有 CGRectZero 框架的 MyView!我在添加容器的同时进行了更改以支持动画。因此,我认为问题与视图层次结构有关。羡慕我!!!

无论如何,感谢所有的帮助者,尤其是 Madhumal Gunetileke,他的回答让我看到了不同的方向。

于 2011-09-08T05:38:38.760 回答