使用Xib导航栏子视图

时间:2015-03-04 00:19:03

标签: ios objective-c iphone

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

#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];
  }];
}

enter image description here

该控件包含一个UITextField。

问题

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

1 个答案:

答案 0 :(得分:0)

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

 [_feedSearchForm.txtSearchField becomeFirstResponder];