您的位置:时时app平台注册网站 > 编程知识 > iOS编制程序常用方法和常见bug修复【时时app平台

iOS编制程序常用方法和常见bug修复【时时app平台

2019-09-14 00:43
1.剔除NSString字符串里面包车型大巴特殊符号
-(NSString*)deleteSpecificSymbolForString:(NSString*)text{ //先创建NSCharacterSet,把需要去除的字符串放在里面 NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"@/::;;¥「」"、[]{}#%-* =_\|~<>$€^•'@#$%^&*_ '""]; //该方法返回的就是去除特殊符号后的字符串 NSString *trimmedString = [text stringByTrimmingCharactersInSet:set]; return trimmedString;}

(BOOL)isIncludeChineseInString:(NSString*)str {}个形式来看上面包车型客车Chinese就通晓了呢,是决断是或不是为中文然后传入布尔值。然后正是其一办法

@interface UISearchController : UIViewController <UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning> @protocol UISearchControllerDelegate <NSObject> //监控SearchController @protocol UISearchResultsUpdating <NSObject> //响应输入的搜索文本内容@interface UISearchBar : UIView <UIBarPositioning, UITextInputTraits> @protocol UISearchBarDelegate <UIBarPositioningDelegate> //监控SearchBar上的行为:输入&各个按钮点击
4.在钦点调整器里面退换状态栏文字颜色
 每一个应用程序,应该都会有统一的导航栏和状态栏风格。但是有时候,也有需要在指定控制器里面修改状态栏的风格,如:播放视频。-viewWillAppear:animated{ [super viewWillAppear:animated]; [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];}-viewWillDisappear:animated{ [super viewWillDisappear:animated]; [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];}

首先映重视帘的是UI所以我们就先从UI开端深入分析然后再起来深入分析这些代码最光彩夺目的有的-------------------找出框。

时时app平台注册网站 1SearchBar结构

8.基于钦定文本,字体,固定宽度或可观,求尺寸
// 根据指定文本,字体和最大高度计算尺寸- sizeWithText:(NSString *)text font:font maxHeight:height{ NSMutableDictionary *attrDict = [NSMutableDictionary dictionary]; attrDict[NSFontAttributeName] = font; CGSize size = [text boundingRectWithSize:CGSizeMake(MAXFLOAT, height) options:NSStringDrawingUsesLineFragmentOrigin attributes:attrDict context:nil].size; return size;}// 根据指定文本,字体和最大宽度计算尺寸- sizeWithText:(NSString *)text font:font maxWidth:width{ NSMutableDictionary *attrDict = [NSMutableDictionary dictionary]; attrDict[NSFontAttributeName] = font; CGSize size = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attrDict context:nil].size; return size;}

时时app平台注册网站 2

iOS完结搜索功效的类:

7.在钦赐调整器中隐蔽导航栏
 有时候,需要在指定控制器中隐藏导航栏,试过好几个方法,或多或少有些坑,下面这个是我认为比较好的: 首先让该控制器成为导航栏的代理: self.navigationController.delegate = self; 然后,实现指定的代理方法: -navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:animated{ if ([viewController isKindOfClass:[self class]]) { [self.navigationController setNavigationBarHidden:YES animated:YES]; } //返回时,在指定控制器重新让导航栏显示 if ([viewController isKindOfClass:[ContactVC class]]) { [self.navigationController setNavigationBarHidden:NO animated:YES]; }}

那四个类就是深扒的切入点。Person是为着合营Model部分。ZYPinYinSearch是协作搜索部分的。提及找出部分即将涉及她写的搜索框_searchBar,何况调用系统方法达成寻找点击事件。在点击里面有如此二个办法 (NSArray *)searchWithOriginalArray:(NSArray

日前页内突显结果

@interface TwoViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchResultsUpdating,UISearchControllerDelegate,UISearchBarDelegate>@property (nonatomic, strong) UITableView *tableView;@property (strong,nonatomic) NSMutableArray *dataList; //原始数据@property (nonatomic, strong) UISearchController * searchController;@property (strong,nonatomic) NSMutableArray *searchList; //搜索结果@end@implementation TwoViewController- viewDidLoad { [super viewDidLoad]; self.automaticallyAdjustsScrollViewInsets = NO; _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, XYScreenW, XYScreenH - 64) style:UITableViewStylePlain]; _tableView.backgroundColor = [UIColor whiteColor]; _tableView.delegate = self; _tableView.dataSource = self; [self.view addSubview:_tableView]; //UISearchController _searchController = [[UISearchController alloc] initWithSearchResultsController:nil]; _searchController.searchResultsUpdater = self; _searchController.delegate = self; _searchController.searchBar.placeholder = @"placeholder"; _searchController.searchBar.showsCancelButton = YES; _searchController.searchBar.frame = CGRectMake(0, 0, XYScreenW, 60); self.tableView.tableHeaderView = _searchController.searchBar; //解决:退出时搜索框依然存在的问题 self.definesPresentationContext = YES;}#pragma mark UISearchResultsUpdating// 每次更新搜索框里的文字,就会调用这个方法- updateSearchResultsForSearchController:(UISearchController *)searchController { NSLog(@"%s",__func__); // 获取搜索框里地字符串 NSString *searchString = searchController.searchBar.text; //搜索逻辑 NSPredicate * predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS %@",searchString]; if (self.searchList!= nil) { //清除结果数据 [self.searchList removeAllObjects]; } //搜索结果 self.searchList = [[_dataList filteredArrayUsingPredicate:predicate] mutableCopy]; //刷新表格 展示搜索结果 [self.tableView reloadData];}// MARK: 懒加载- (NSMutableArray *) dataList { if (_dataList == nil) { _dataList = [NSMutableArray arrayWithCapacity:100]; for (NSInteger i=0; i<100; i  ) { [_dataList addObject:[NSString stringWithFormat:@"%ld-FlyElephant",i]]; } } return _dataList;}- (NSMutableArray *) searchList { if (_searchList == nil) { _searchList = [NSMutableArray array]; } return _searchList;}#pragma mark - UITableViewDataSource- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if (self.searchController.active) { //正在展示搜索结果 return [self.searchList count]; }else{ return [self.dataList count]; }}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *flag=@"cellFlag"; UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:flag]; if (cell==nil) { cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:flag]; } if (self.searchController.active) { [cell.textLabel setText:self.searchList[indexPath.row]]; } else{ [cell.textLabel setText:self.dataList[indexPath.row]]; } return cell;}
5.点击步向找出调控器时,自动掸出键盘,让找出框步入编辑状态

当点击寻找时,步向寻觅调控器,使用系统自带的寻找框,searchController.searchBar,步向时,自动实现如下图的功力

时时app平台注册网站 3效果图.png

找了过多主意,下边那些是有效措施:

- viewDidAppear:animated { [super viewDidAppear:animated]; [self performSelector:@selector(showKeyboard) withObject:nil afterDelay:0];}- showKeyboard { [self.searchController.searchBar becomeFirstResponder];}

时时app平台注册网站 4

区别:

UISearchDisplayController自带显示结果的TableView, 使用UISearchDisplayController的时候,寻觅结果的来得tableView系统已经帮我们封装好;

不过,使用UISearchController,我们需求提供四个搜索结果的来得TableView.

3.确定NSString字符串里面有未有瑞典语字母
-estimateStringContainEnglish:(NSString*)text{ if{ for (int i=0; i<text.length; i  ) { NSRange range = NSMakeRange; NSString *subString = [text substringWithRange:range]; const char *cString = [subString UTF8String]; if (strlen == 1){ //代表有英文 return YES; } } } return NO;}

作者精心的做了这么不为空的推断,当然如此的剖断是相应的到底不这么判定有比相当大可能会挑起bug,然则依旧以为要提一下,因为自个儿就时常忘了写。下面便是依照不一样传入参数的格式写的。

重大介绍:

2.论断NSString字符串里面有未有汉字
-estimateStringContainChinese:(NSString*)text{ if{ for (int i=0; i<text.length; i  ) { NSRange range = NSMakeRange; NSString *subString = [text substringWithRange:range]; const char *cString = [subString UTF8String]; if (strlen == 3){ //代表有汉字 return YES; } } } return NO;}

- (NSRange)rangeOfString:(NSString *)searchString

iOS8.0弃用了的UISearchDisplayController,就不介绍了。

9.给UILabel设置行间距,字间距等富文本属性,并图谋中度
//给UILabel设置行间距和字间距-setLabelSpace:label withValue:(NSString*)str withFont:font { NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init]; paraStyle.lineBreakMode = NSLineBreakByCharWrapping; //结尾部分的文字省略方式 paraStyle.alignment = NSTextAlignmentLeft; //文本对齐方式 paraStyle.lineSpacing = 7; //设置行间距 paraStyle.hyphenationFactor = 1.0; //连字属性 在iOS,唯一支持的值分别为0和1 paraStyle.firstLineHeadIndent = 0.0; //首行缩进 paraStyle.paragraphSpacingBefore = 0.0; //段首行空白空间 paraStyle.headIndent = 0; //整体缩进 paraStyle.paragraphSpacing = 15; //段与段之间的间距 //设置字间距 NSKernAttributeName:@1.5f NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paraStyle, NSKernAttributeName:@1.5f}; NSAttributedString *attributeStr = [[NSAttributedString alloc] initWithString:str attributes:dic]; label.attributedText = attributeStr;}//计算UILabel的高度-getSpaceLabelHeight:(NSString*)str withFont:font withWidth:width { NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init]; paraStyle.lineBreakMode = NSLineBreakByCharWrapping; paraStyle.alignment = NSTextAlignmentLeft; paraStyle.lineSpacing = 7; paraStyle.hyphenationFactor = 1.0; paraStyle.firstLineHeadIndent = 0.0; paraStyle.paragraphSpacingBefore = 0.0; paraStyle.headIndent = 0; paraStyle.paragraphSpacing = 15; NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paraStyle, NSKernAttributeName:@1.5f}; CGSize size = [str boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size; return size.height;}

下一场就赶到我们的完结层,那一个传值的论断还会有跳转笔者就不用介绍了信任我们都懂,那有的私有认为依然很轻巧的,代码工整。我们来扒一下那个工程的主干部分ZYSearchViewController。依照不一样的type举行差别的管理本身也是毫无介绍了。上面正是依赖字符串来进展检索然后展现。他用了四个数组进行收纳,借让你只是想调用知道这一个也就够了,把Lib直接拖进去然后调用方法,但是大家要深扒一下总体育工作程。

UISearchResultsUpdating & UISearchControllerDelegate

#pragma mark UISearchResultsUpdating// 每次更新搜索框里的文字,就会调用这个方法// Called when the search bar's text or scope has changed or when the search bar becomes first responder.// 根据输入的关键词及时响应:里面可以实现筛选逻辑 也显示可以联想词- updateSearchResultsForSearchController:(UISearchController *)searchController { NSLog(@"%s",__func__); // 获取搜索框里地字符串 NSString *searchString = searchController.searchBar.text; //一般在这里实现搜索的逻辑 & 展示搜索结果}#pragma mark UISearchControllerDelegate// These methods are called when automatic presentation or dismissal occurs.// They will not be called if you present or dismiss the search controller yourself.- willPresentSearchController:(UISearchController *)searchController { NSLog(@"%s",__func__);}- didPresentSearchController:(UISearchController *)searchController{ NSLog(@"%s",__func__);}- willDismissSearchController:(UISearchController *)searchController{ NSLog(@"%s",__func__);}- didDismissSearchController:(UISearchController *)searchController{ NSLog(@"%s",__func__);}// Called after the search controller's search bar has agreed to begin editing or when 'active' is set to YES. If you choose not to present the controller yourself or do not implement this method, a default presentation is performed on your behalf.- presentSearchController:(UISearchController *)searchController { NSLog(@"%s",__func__);}

福寿双全搜索的办法:

  1. iOS 8.0和事先的版本:UISearchBar UISearchDisplayController(这里就不详细介绍了)
  2. iOS 8.0和上述的本子:UISearchController & UISearchBar
    • UISearchController 当前页面显示搜索结果
    • UISearchController 新调控器显示寻觅结果
    • 独自选择UISearchBar

Demo:

6.修改系统自带寻找框的UI
 系统自带的搜索框,使用方便快捷,但是有时候它的外观与要求不符,这时候就需要我们来对系统搜索框进行一些修改for (UIView* subview in [[self.searchController.searchBar.subviews lastObject] subviews]) { //相当于UITextField,输入框,可以修改背景颜色等 if ([subview isKindOfClass:NSClassFromString(@"UISearchBarTextField")]) { UITextField *textField = (UITextField*)subview; [textField setBackgroundColor:COLOR_RGB(238, 238, 238)]; } //相当于UIButton,搜索框右侧的Cancle按钮,可以修改默认文字等 if ([subview isKindOfClass:NSClassFromString(@"UINavigationButton")]) { UIButton* cancle = (UIButton*)subview; [cancle setTitle:@"取消" forState:UIControlStateNormal]; [cancle setTitleColor:COLOR_RGB(82, 184, 255) forState:UIControlStateNormal]; } //相当于UIView,搜索框的背景view,一般将它去掉,然后自己添加一层背景view if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) { [subview removeFromSuperview]; UIView* back = [[UIView alloc]initWithFrame:self.searchController.searchBar.bounds]; back .backgroundColor = [UIColor whiteColor]; [self.searchController.searchBar insertSubview:back atIndex:0]; } }

时时app平台注册网站 5

iOS 8.0-:UISearchBar UISearchDisplayController

*)originalArray andSearchText:(NSString *)searchText

黑技术

BUG:

使用UISearchController完结搜索效果时,当从搜索页再次来到时,UISearchController的UISearchBar不收敛!

原因:

UISearchController承接自UIViewController,约等于说UISearchController自己也包涵多个View。但大家在动用UISearchController的时候从不将UISearchController自带的View增添在self.view上,也正是未钦定那么些controller呈现UISearchController自带View上的控件。

之所以,UISearchController的searchBar不会跟随搜索页面移动而跟随寻找页的退出联合未有。

化解办法:

UIViewController里有三个特性:@property (nonatomic,assign)BOOL definesPresentationContext;

这一属性决定了那一个父调整器的View,将会以优先于UIModalPresentationCurrentContext这种表现方式来呈现本身的View。若无父调控器设置这一本性,那么显示的调控器将会是根视图调整器。

一旦在要兑现搜索效能的调整器里安装:== self.definesPresentationContext = YES; == 就可以兑现UISearchController的UISearchBar跟随寻找页面一齐滑动。一同消失。

self.definesPresentationContext = YES; 

注意:

  1. 如果不设置:self.definesPresentationContext = YES;那么

    假使设置了hidesNavigationBarDuringPresentation=YES,在步向编辑格局的时候会形成searchBar看不见。

    假诺设置了hidesNavigationBarDuringPresentation=NO,在步向编辑方式会促成中度为64的空域区域出现。

  2. 万一设置:self.definesPresentationContext = YES;

    若果设置了hidesNavigationBarDuringPresentation=YES,在步向编辑情势会符合规律展现和应用。

    若是设置了hidesNavigationBarDuringPresentation=NO,在步入编辑形式会导致找寻框向下偏移64.

关于搜索结果分界面

第一:几时展现结果分界面?

当顾客开头编写制定寻觅框时,会触发updateSearchResultsForSearchController:(UISearchController *)searchController代办方法。UISearchController就能够触发willPresentSearchController:(UISearchController *)searchController代办方法,自动起始体现找寻结果分界面:

  • 当前界面显得:会自动突显当前页面包车型大巴View 来浮现寻找结果
  • 新调控器分界面显得: 会自行呈现新调节器的view 来展现搜索结果

此时,UISearchController步入Presentation方式,active的值是YES。可用来做判别是或不是正在查找。

那份代码用的是SB跟代码集成,看到这几个代码现在深深的认识到SB跟代码结合的光明。四个思疑的便是那多个法子的涉嫌,那些是因为用到了SB的从头到尾的经过所以能够那样写,利用了SB自带方法以及大家一般见的拖拽能够兑现传值也能够达成跳转。一同首不明了为什么写了五个格局显然叁个措施就足以兑现,探究了一晃这么写更简短大方而且不便于出错(作者也不得不及此敞亮了,若是有好的理念补偿一下本人的知识库)。

  • 运用UISearchController来极度方便的丰裕找出框,UISearchController带有SearchBar属性,无需单独成立。

andSearchByPropertyName:(NSString *)propertyName,那么些法子是促成判别输入内容是或不是是汉语以及根据拼音找出重回数组数据。

先熟稔SearchBar的组织,它是三个UIView。全体api都围绕着SearchBar上的控件举办定制:

(NSString*)chineseConvertToPinYin:(NSString*)chinese,那么些点子里面运用到HanyuPinyinOutputFormat,它但是造福中华人民共和国人的把粤语转化成汉语拼音的类。转化成拼音以往就用到

  • 但是,iOS8.0弃用了UISearchDisplayController。

options:(NSStringCompareOptions)mask;那个连串方法了。非常多艺术也许不曾分析出来,小编会积极的。

UISearchBarDelegate

// FIXME: UISearchBarDelegate// return NO to not become first responder- searchBarShouldBeginEditing:(UISearchBar *)searchBar{ NSLog(@"%s",__func__); return YES;}// called when text starts editing- searchBarTextDidBeginEditing:(UISearchBar *)searchBar { NSLog(@"%s",__func__); NSLog(@"searchBar.text = %@",searchBar.text);}// return NO to not resign first responder- searchBarShouldEndEditing:(UISearchBar *)searchBar { NSLog(@"%s",__func__); return YES;}// called when text ends editing- searchBarTextDidEndEditing:(UISearchBar *)searchBar { NSLog(@"%s",__func__); NSLog(@"searchBar.text = %@",searchBar.text);}// called before text changes- searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:range replacementText:(NSString *)text { NSLog(@"%s",__func__); NSLog(@"searchBar.text = %@",searchBar.text); return YES;}// called when text changes (including clear)- searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText { NSLog(@"%s",__func__); NSLog(@"searchBar.text = %@",searchBar.text);}// called when keyboard search button pressed 键盘搜索按钮- searchBarSearchButtonClicked:(UISearchBar *)searchBar { NSLog(@"%s",__func__); NSLog(@"searchBar.text = %@",searchBar.text);}// called when bookmark button pressed- searchBarBookmarkButtonClicked:(UISearchBar *)searchBar{ NSLog(@"%s",__func__);}// called when cancel button pressed- searchBarCancelButtonClicked:(UISearchBar *)searchBar{ NSLog(@"%s",__func__);}// called when search results button pressed- searchBarResultsListButtonClicked:(UISearchBar *)searchBar{ NSLog(@"%s",__func__);}// selecte ScopeButton- searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope { NSLog(@"%s",__func__); NSLog(@"selectedScope = %ld",selectedScope);}

@interface UISearchController : UIViewController <UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning>NS_CLASS_AVAILABLE_IOS//创建- (instancetype)initWithSearchResultsController:(nullable UIViewController *)searchResultsController;// Pass nil if you wish to display search results in the same view that you are searching.// searchResultsController 用来显示结果//常用属性@property (nonatomic, strong, readonly) UISearchBar *searchBar;@property (nullable, nonatomic, strong, readonly) UIViewController *searchResultsController;@property (nonatomic, assign, getter = isActive) BOOL active;//The presented state of the search interface. //显示结果的意思//This property to determine whether the search results are displayed.//You can set this property to YES to force the search interface to appear, even if the user has not taps in the search field.//The default value of this property is NO.@property (nullable, nonatomic, weak) id <UISearchControllerDelegate> delegate;@property (nullable, nonatomic, weak) id <UISearchResultsUpdating> searchResultsUpdater;//显示@property (nonatomic, assign) BOOL dimsBackgroundDuringPresentation; //设置是否在搜索时显示半透明背景@property (nonatomic, assign) BOOL obscuresBackgroundDuringPresentation NS_AVAILABLE_IOS; //whether the underlying content is obscured during a search.@property (nonatomic, assign) BOOL hidesNavigationBarDuringPresentation; //设置是否在搜索时隐藏导航栏@end

iOS 8.0 :UISearchController

@interface UISearchBar : UIView <UIBarPositioning, UITextInputTraits>//创建- (instancetype)init;- (instancetype)initWithFrame:frame;- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder;//设置//文字内容@property(nullable,nonatomic,copy) NSString *text; // current/starting search text@property(nullable,nonatomic,copy) NSString *prompt; // default is nil@property(nullable,nonatomic,copy) NSString *placeholder; // default is nil//样式设置@property(nonatomic) UIBarStyle barStyle; // default is UIBarStyleDefault @property (nonatomic) UISearchBarStyle searchBarStyle; //searchBarStyle样式 typedef enum UISearchBarStyle : NSUInteger { UISearchBarStyleDefault, UISearchBarStyleProminent, UISearchBarStyleMinimal } UISearchBarStyle;@property(null_resettable, nonatomic,strong) UIColor *tintColor;@property(nullable, nonatomic,strong) UIColor *barTintColor; // default is nil@property(nonatomic,assign,getter=isTranslucent) BOOL translucent; //设置是否半透明- setBackgroundImage:(nullable UIImage *)backgroundImage forBarPosition:(UIBarPosition)barPosition barMetrics:(UIBarMetrics)barMetrics;- (nullable UIImage *)backgroundImageForBarPosition:(UIBarPosition)barPosition barMetrics:(UIBarMetrics)barMetrics;@property(nullable, nonatomic,strong) UIImage *backgroundImage;- setSearchFieldBackgroundImage:(nullable UIImage *)backgroundImage forState:(UIControlState)state;- (nullable UIImage *)searchFieldBackgroundImageForState:(UIControlState)state;@property(nonatomic) UIOffset searchFieldBackgroundPositionAdjustment;@property(nonatomic) UIOffset searchTextPositionAdjustment;//UISearchBarIcon(searchBar上的几个按钮) typedef enum UISearchBarIcon : NSInteger { UISearchBarIconSearch, UISearchBarIconClear, UISearchBarIconBookmark, UISearchBarIconResultsList } UISearchBarIcon;//各个按钮的图标- setImage:(nullable UIImage *)iconImage forSearchBarIcon:(UISearchBarIcon)icon state:(UIControlState)state;//各个按钮的位置- (nullable UIImage *)imageForSearchBarIcon:(UISearchBarIcon)icon state:(UIControlState)state;// 按钮的位置- setPositionAdjustment:adjustment forSearchBarIcon:(UISearchBarIcon)icon;- positionAdjustmentForSearchBarIcon:(UISearchBarIcon)icon;//Custom显示@property (nullable, nonatomic, readwrite, strong) UIView *inputAccessoryView;@property (nonatomic, readonly, strong) UITextInputAssistantItem *inputAssistantItem NS_AVAILABLE_IOS ; //Shown on top of the keyboard when search is engaged.//Buttons@property(nonatomic) BOOL showsBookmarkButton; // default is NO@property(nonatomic) BOOL showsCancelButton; // default is NO- setShowsCancelButton:showsCancelButton animated:animated;@property(nonatomic) BOOL showsSearchResultsButton; // default is NO@property(nonatomic, getter=isSearchResultsButtonSelected) BOOL searchResultsButtonSelected; // default is NO//ScopeBar@property(nonatomic) BOOL showsScopeBar; // default is NO. if YES, shows the scope bar. call sizeToFit: to update frame@property(nullable, nonatomic,copy) NSArray<NSString *> *scopeButtonTitles ; // array of NSStrings. no scope bar shown unless 2 or more items@property(nonatomic) NSInteger selectedScopeButtonIndex; // index into array of scope button titles. default is 0. ignored if out of range- setScopeBarButtonBackgroundImage:(nullable UIImage *)backgroundImage forState:(UIControlState)state;- (nullable UIImage *)scopeBarButtonBackgroundImageForState:(UIControlState)state;@property(nullable, nonatomic,strong) UIImage *scopeBarBackgroundImage;- setScopeBarButtonDividerImage:(nullable UIImage *)dividerImage forLeftSegmentState:(UIControlState)leftState rightSegmentState:(UIControlState)rightState;- (nullable UIImage *)scopeBarButtonDividerImageForLeftSegmentState:(UIControlState)leftState rightSegmentState:(UIControlState)rightState;- setScopeBarButtonTitleTextAttributes:(nullable NSDictionary<NSString *, id> *)attributes forState:(UIControlState)state;- (nullable NSDictionary<NSString *, id> *)scopeBarButtonTitleTextAttributesForState:(UIControlState)state;@property(nullable,nonatomic,weak) id<UISearchBarDelegate> delegate;@end

在新调节器显示搜索结果

@interface ThreeViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchResultsUpdating,UISearchControllerDelegate,UISearchBarDelegate>@property (nonatomic, strong) UITableView *tableView;@property (strong,nonatomic) NSMutableArray *dataSource; //原始数据@property (nonatomic, strong) UISearchController *searchController;@property (strong,nonatomic) NSMutableArray *searchResults; //搜索结果@property (strong,nonatomic) ResultVC *resultVC; //搜索结果展示控制器@end - viewDidLoad { [super viewDidLoad]; self.automaticallyAdjustsScrollViewInsets = NO; //tableView _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, XYScreenW, XYScreenH - 64) style:UITableViewStylePlain]; _tableView.backgroundColor = [UIColor whiteColor]; _tableView.delegate = self; _tableView.dataSource = self; [self.view addSubview:_tableView]; //UISearchController //创建显示搜索结果控制器 _resultVC = [[ResultVC alloc] init]; _searchController = [[UISearchController alloc] initWithSearchResultsController:_resultVC]; _searchController.searchResultsUpdater = self; _searchController.delegate = self; _searchController.searchBar.placeholder = @"placeholder"; _searchController.searchBar.showsCancelButton = YES; _searchController.hidesNavigationBarDuringPresentation = YES; //搜索时隐藏导航栏 _searchController.searchBar.delegate = self; _searchController.searchBar.frame = CGRectMake(0, 0, XYScreenW,60); self.tableView.tableHeaderView = _searchController.searchBar; //解决:退出时搜索框依然存在的问题 self.definesPresentationContext = YES;}#pragma mark - UITableViewDelegate, UITableViewDataSource- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // 如果用户正在搜索,则返回搜索结果的count,否则直接返回数据源数组的count; if (self.searchController.active) { return self.searchResults.count; }else { return self.dataSource.count; }}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kUITableViewCellIdentifier]; if  { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:kUITableViewCellIdentifier]; } // 如果用户正在搜索,则返回搜索结果对应的数据,否则直接返回数据数组对应的数据; if (self.searchController.active) { cell.textLabel.text = _searchResults[indexPath.row]; }else { cell.textLabel.text = _dataSource[indexPath.row]; } return cell;}#pragma mark UISearchResultsUpdating// 每次更新搜索框里的文字,就会调用这个方法// Called when the search bar's text or scope has changed or when the search bar becomes first responder.// 根据输入的关键词及时响应:里面可以实现筛选逻辑 也显示可以联想词- updateSearchResultsForSearchController:(UISearchController *)searchController { NSLog(@"%s",__func__); //会自动显示新控制器的view 来展示搜索结果 //获取搜索框里地字符串 NSString *searchString = searchController.searchBar.text; // 谓词 /** 1.BEGINSWITH : 搜索结果的字符串是以搜索框里的字符开头的 2.ENDSWITH : 搜索结果的字符串是以搜索框里的字符结尾的 3.CONTAINS : 搜索结果的字符串包含搜索框里的字符 [c]不区分大小写[d]不区分发音符号即没有重音符号[cd]既不区分大小写,也不区分发音符号。 */ // 创建谓词 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS [CD] %@", searchString]; // 如果搜索框里有文字,就按谓词的匹配结果初始化结果数组,否则,就用字体列表数组初始化结果数组。 if (_searchResults != nil && searchString.length > 0) { //清除搜索结果 [_searchResults removeAllObjects]; _searchResults = [NSMutableArray arrayWithArray:[_dataSource filteredArrayUsingPredicate:predicate]]; } else if (searchString.length == 0) { _searchResults = [NSMutableArray arrayWithArray:_dataSource]; } //显示搜索结果 //在新控制器调用刷新页面的方法 self.resultVC.results = _searchResults; }// MARK: 数据源- (NSMutableArray *) dataSource { if (_dataSource == nil) { _dataSource = [NSMutableArray arrayWithArray:[UIFont familyNames]]; } return _dataSource;}- (NSMutableArray *) searchResults { if (_searchResults == nil) { _searchResults = [NSMutableArray array]; } return _searchResults;}//在新控制器里://在获得搜索结果数据时,调用刷新页面的方法@property (nonatomic,strong) NSArray *results;-setResults:(NSArray *)results { NSLog(@"%s",__FUNCTION__); _results = results; [self.tableView reloadData];}

时时app平台注册网站 6SearchBar结构

也得以单独行使UISearchBar来贯彻寻觅效果,通过代理方法监察和控制UISearchBar上的操作来支配怎么样体现结果:

-viewDidLoad { [super viewDidLoad]; //一般不会单独使用searchBar,都是结合UISearchController使用 _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(30, 100, 350, 60)]; _searchBar.delegate = self; _searchBar.placeholder = @"placeholder"; _searchBar.prompt = @"prompt"; //_searchBar.text = @"直接搜"; _searchBar.searchBarStyle = UISearchBarStyleDefault; //各个按钮的图标 [_searchBar setImage:[UIImage imageNamed:@"test.jpg"] forSearchBarIcon:UISearchBarIconBookmark state:UIControlStateNormal]; //各个按钮的位置 [_searchBar setPositionAdjustment:UIOffsetMake forSearchBarIcon:UISearchBarIconSearch]; _searchBar.showsBookmarkButton = YES; _searchBar.showsCancelButton = YES; _searchBar.showsSearchResultsButton = YES; //与BookmarkButton重叠 _searchBar.showsScopeBar = YES; _searchBar.scopeButtonTitles = @[@"scope01",@"scope02",@"scope03"]; [self.view addSubview:_searchBar];}// FIXME: UISearchBarDelegate// called when keyboard search button pressed 键盘搜索按钮- searchBarSearchButtonClicked:(UISearchBar *)searchBar { NSLog(@"%s",__func__); NSLog(@"searchBar.text = %@",searchBar.text); //可以在这里实现跳转新控制器 //通过searchBar.text 参数来请求搜索结果}// called when bookmark button pressed- searchBarBookmarkButtonClicked:(UISearchBar *)searchBar{ NSLog(@"%s",__func__);}// called when cancel button pressed- searchBarCancelButtonClicked:(UISearchBar *)searchBar{ NSLog(@"%s",__func__);}// called when search results button pressed- searchBarResultsListButtonClicked:(UISearchBar *)searchBar{ NSLog(@"%s",__func__);}// selecte ScopeButton- searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope { NSLog(@"%s",__func__); NSLog(@"selectedScope = %ld",selectedScope);}

Demo:

本文由时时app平台注册网站发布于编程知识,转载请注明出处:iOS编制程序常用方法和常见bug修复【时时app平台

关键词: