Swift - 带结果列表的搜索条(UISearchDisplayController)的用法
作者:hangge | 2015-02-04 15:26
(注:自iOS8起,苹果便废弃UISearchDisplayController的使用,改为使用UISearchController来实现类似功能,可参考我的另一篇文章“Swift - 使用UISearchController实现带搜索栏的表格”)
下面提供了一个使用样例,同时通过代码定制Search Bar的一些属性来实现自定义的外观和效果,并且展示用于选择搜索范围的分段条的用法。
效果图如下:


--- ViewController.swift ---
import UIKit
class ViewController: UIViewController,UISearchBarDelegate {
// 引用通过storyboard创建的控件
@IBOutlet var searchDisplay: UISearchDisplayController!
// 所有组件
var ctrls:[String] = ["Label","Button1-初级","Button1-高级","Button2-初级","Button2-高级","Switch"]
// 搜索匹配的结果,Table View使用这个数组作为datasource
var ctrlsel:[String] = []
override func viewDidLoad() {
super.viewDidLoad()
// 起始加载全部内容
self.ctrlsel = self.ctrls
// 注册TableViewCell
self.searchDisplay.searchResultsTableView.registerClass(UITableViewCell.self,
forCellReuseIdentifier: "SwiftCell")
// 设置文本提示
self.searchDisplay.searchBar.placeholder = "输入搜索信息"
// 可以设置初始值
//self.searchDisplay.searchBar.text = "b"
// 设置搜索栏提示信息
self.searchDisplay.searchBar.prompt = "搜索组件名称"
// 不显示Search Bar边框
self.searchDisplay.searchBar.searchBarStyle = UISearchBarStyle.Minimal
// 显示分段条
self.searchDisplay.searchBar.showsScopeBar = true
self.searchDisplay.searchBar.scopeButtonTitles = ["全部","初级","高级"]
}
// 返回表格行数(也就是返回控件数)
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return self.ctrlsel.count
}
// 创建各单元显示内容(创建参数indexPath指定的单元)
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!)
-> UITableViewCell!
{
// 为了提供表格显示性能,已创建完成的单元需重复使用
let identify:String = "SwiftCell"
// 同一形式的单元格重复使用,在声明时已注册
let cell = self.searchDisplay.searchResultsTableView.dequeueReusableCellWithIdentifier(
identify, forIndexPath: indexPath) as UITableViewCell
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
cell.textLabel?.text = self.ctrlsel[indexPath.row]
return cell
}
// 搜索代理UISearchBarDelegate方法,每次改变搜索内容时都会调用
func searchBar(searchBar: UISearchBar!, textDidChange searchText: String!) {
self.searchText = searchText
searchCtrls()
}
// 选择分段条时调用
func searchBar(searchBar: UISearchBar!, selectedScopeButtonIndexDidChange selectedScope: Int) {
print(selectedScope)
searchCtrls();
}
// 保存搜索内容
var searchText:String = ""
// 搜索过滤
func searchCtrls() {
// 没有搜索内容时显示全部组件
if self.searchText == "" {
self.ctrlsel = self.ctrls
}
else {
var scope = self.searchDisplay.searchBar.selectedScopeButtonIndex;
// 匹配用户输入内容的前缀
self.ctrlsel = []
for ctrl in self.ctrls {
let lc = ctrl.lowercaseString
if lc.hasPrefix(self.searchText) {
if (scope == 0 || (scope == 1 && lc.hasSuffix("初级"))
|| (scope == 2 && lc.hasSuffix("高级"))) {
self.ctrlsel.append(ctrl)
}
}
}
}
// 不需要刷新Table View显示
// self.searchDisplay.searchResultsTableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
--- Main.storyboard ---
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="6254" systemVersion="14B25" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="BYZ-38-t0r">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="6247"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="ViewController" customModule="SwiftInAction_008_013" customModuleProvider="target" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
<viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<searchBar contentMode="redraw" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="514-A1-KsH">
<rect key="frame" x="0.0" y="28" width="320" height="44"/>
<textInputTraits key="textInputTraits"/>
<connections>
<outlet property="delegate" destination="BYZ-38-t0r" id="HNb-H1-SIO"/>
</connections>
</searchBar>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
</view>
<connections>
<outlet property="searchDisplay" destination="Lnz-5r-UWS" id="vbY-sQ-4L2"/>
<outlet property="searchDisplayController" destination="Lnz-5r-UWS" id="Kly-uU-7J1"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
<searchDisplayController id="Lnz-5r-UWS">
<connections>
<outlet property="delegate" destination="BYZ-38-t0r" id="889-9H-eic"/>
<outlet property="searchBar" destination="514-A1-KsH" id="jg7-8Q-dht"/>
<outlet property="searchContentsController" destination="BYZ-38-t0r" id="S5V-Yk-ta3"/>
<outlet property="searchResultsDataSource" destination="BYZ-38-t0r" id="5rb-QW-jlM"/>
<outlet property="searchResultsDelegate" destination="BYZ-38-t0r" id="9rR-uv-SDW"/>
</connections>
</searchDisplayController>
</objects>
</scene>
</scenes>
</document>
全部评论(1)
不出结果,tableview什么也不显示
站长回复:iOS8起UISearchDisplayController已经被废弃使用,改用UISearchController实现类似功能,我也写了篇文章介绍UISearchController的使用,你可以看下。