【问题标题】:Navigation Bar Subview with Xib带有 Xib 的导航栏子视图
【发布时间】:2015-05-04 20:32:27
【问题描述】:

我正在开发的应用程序中遇到了一个小问题。我想扩展导航栏以支持类似控件的搜索字段。用户将单击导航栏右上角按钮中的搜索按钮,然后导航栏将展开以显示具有搜索和取消按钮的搜索字段。我使用此实现实现了以下目标:

#import <UIKit/UIKit.h> //Xib header 

@interface SearchForm : UIView
@property (weak, nonatomic) IBOutlet UITextField *txtSearchField;
@property (weak, nonatomic) IBOutlet UIButton *btnCancel;
- (IBAction)btnCancel:(id)sender;
@property (weak, nonatomic) IBOutlet UIButton *btnSearch;
- (IBAction)btnSearch:(id)sender;

@end


#import "SearchForm.h" //Xib implementation


@interface SearchForm () <UITextFieldDelegate>
{

}

@end

@implementation SearchForm

- (id)initWithCoder:(NSCoder *)aDecoder
{
  if ((self = [super initWithCoder:aDecoder]))
  {
    self.txtSearchField.delegate = self;
  }
  return self;
}

- (IBAction)btnCancel:(id)sender
{
  DLog();

}

- (IBAction)btnSearch:(id)sender
{

}

#pragma mark Text Field Delegate

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
  //TODO:Callback to feed.
  return YES;
}


//Main View Controller
-(SearchForm *)feedSearchForm
{
  if(!_feedSearchForm)
  {
    _feedSearchForm = [[[NSBundle mainBundle] loadNibNamed:@"SearchForm" owner:self options:nil] objectAtIndex:0];
     //I think this frame is the problem but I'm not sure
    _feedSearchForm.frame = CGRectMake(0, self.navigationController.navigationBar.frame.size.height, 320, STREAM_LIST_TOP_CONSTRAINT_HEIGHT);
  }

  return _feedSearchForm;
}

//Exposes the search field 
-(void)expandSearchField:(id)sender 
{
  tableVerticalVariableConstraint.constant = STREAM_LIST_TOP_CONSTRAINT_HEIGHT;


  [UIView animateWithDuration:0.4 animations:^{
     [self.navigationController.navigationBar addSubview:self.feedSearchForm];
    [self.view layoutIfNeeded];
  }];
}

控件内部包含一个 UITextField。

问题

但是,即使此代码完全符合我的要求,但当我在文本字段内单击时,键盘永远不会显示。这就像触摸没有被注册。我尝试注释掉我明确设置 xib 框架的代码,当我这样做时,触摸事件被识别,但 xib 位于导航栏的顶部,看起来不像是栏的自然扩展我需要的。任何建议或提示将不胜感激。

【问题讨论】:

    标签: ios objective-c iphone


    【解决方案1】:

    您可以尝试将以下代码添加到您的“-(SearchForm *)feedSearchForm”方法中。

     [_feedSearchForm.txtSearchField becomeFirstResponder];
    

    【讨论】:

    • 我在 feedSearchForm 方法以及 xib 的 init 子类中都尝试了这种方法,这两种方法都不起作用。我在其他帖子上读到你不能做我想做的事情,因为导航栏有一个设定的高度,导航栏上的子视图不一定是视图控制器的一部分。我可能在这方面错了,但这就是我到目前为止所学到的。