我为我的应用创建了一个自定义搜索栏,这是课程: .H
@interface SearchView : UIView <UITextFieldDelegate, UISearchBarDelegate>
@property (nonatomic, strong) UITextField *searchField;
@property (nonatomic, strong) UIButton *searchButton;
@end
的.m
@implementation SearchView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
CGRect frame = CGRectMake(0, 0, 35, 35);
[self.searchButton sizeToFit];
self.alpha = 0.6;
self.backgroundColor = [UIColor colorWithRed:206/255.0 green:206/255.0 blue:206/255.0 alpha:.8];
self.searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
//[self.searchButton addTarget:self action:@selector(performSearchQuery) forControlEvents:UIControlEventTouchUpInside];
[self.searchButton setImage:[UIImage imageNamed:@"SearchIcon2"] forState:UIControlStateNormal];
//[self.searchButton sizeToFit];
//self.searchButton.bounds.size.height = ;
self.searchButton.frame = frame;
// self.searchButton.right = frame.size.width - kPadding;
[self addSubview:self.searchButton];
self.searchField = [[UITextField alloc] initWithFrame:CGRectMake(43, -5, 270, 50)];
//self.searchField.placeholder = [@"Search..." uppercaseString];
self.searchField.delegate = self;
self.searchField.autocorrectionType = UITextAutocorrectionTypeNo;
self.searchField.autocapitalizationType = UITextAutocapitalizationTypeWords;
self.searchField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
self.searchField.returnKeyType = UIReturnKeySearch;
self.searchField.clearsOnBeginEditing = YES;
self.searchField.clearButtonMode = UITextFieldViewModeWhileEditing;
[self addSubview:self.searchField];
}
return self;
}
我正在尝试获取searchBarSearchButtonClicked:
委托方法的功能。
这是代码(taskListViewController):
·H
@interface TaskListViewController : UIViewController <UITableViewDelegate,UITableViewDataSource, UISearchBarDelegate, UITextFieldDelegate, ScavengerAPIGetTaskListDelegate>{
SearchView *searchView;
}
的.m
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
searchBar = (UISearchBar *)searchView;
[self didTapSearchButton];
}
- (IBAction)didTapSearchButton
{
NSString *searchTerm = searchView.searchField.text;
if ([searchTerm isEqualToString:@""]) {
[self.view endEditing:YES];
return ;
}
[searchView resignFirstResponder];
NSArray *results = [[CoreDataManager sharedInstance] fetchTaskByName:searchTerm];
[tasks removeAllObjects];
[tasks addObjectsFromArray:results];
[self.view endEditing:YES];
[taskTable reloadData];
}
所以我在searchView类和TaskListViewController上设置了uisearchBarDelegate。它是不是被调用的原因,因为我是uiview而不是uisearchBar的子类?如果您需要更多代码/细节,请告诉我们!谢谢!
答案 0 :(得分:1)
您已经创建了一个自定义搜索视图,因此建议您让您的类实现自己的委托搜索方法,而不是使用现有的UISearchBar来区分并使代码更具可读性。
您应该为SearchView
班级
在这里,您可以参考如何创建自己的一个 How to make Custom Delegate in iOS app
创建后TaskListViewController
可以符合该委托,并且可以在点击searchButton时调用searchview中的方法,以便TaskListViewController接收它