【发布时间】:2016-11-14 21:21:55
【问题描述】:
我有 2 个控制器: Controller1 和 Controller2 用作 SubView 。 Controller1 附加了一个 UISearchBar , OnClick Controller2 显示为带有 TableView 的 SubView 。当用户在 SearchBar 中输入时,我可以使用它来获得结果
// Controller1
@IBOutlet weak var mySearch: UISearchBar!
override func viewDidLoad() {
super.viewDidLoad()
mySearch.delegate = self
// Do any additional setup after loading the view.
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String){
if let text = searchBar.text {
let search = text.trimmingCharacters(in: .whitespaces)
_ = search
}
}
现在我最大的问题是获取我在 searchText 中获得的值并将其传递给 Controller2,我该怎么做呢? Controller2 执行 HTTP Post 请求,并将使用 Controller1 中 SearchText 的值。这是Controller2中的代码
class Controller2: UIViewController,UITableViewDataSource {
@IBOutlet weak var TableSource: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
TableSource.dataSource = self
// I would like to get value of SearchText here so that I can
// send it as a parameter in my HttpPost request
session.dataTask(with:request, completionHandler: {(data, response, error) in
if error != nil {
} else {
do {
// get Json Data
} catch let error as NSError {
print(error)
}
print(self.locations)
}
}).resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) -> Int {
return locations.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Registration_Search", for: indexPath)
return cell
}
}
这是在 Controller1 中,点击 UISearchBar 这就是我将 Controller2 作为子视图的方式
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
Location_Search.showsCancelButton = true
let Popup = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Controller2") as! Controller2
self.addChildViewController(Popup)
Popup.view.frame = self.Controller2.frame
self.view.addSubview(Popup.view)
Popup.didMove(toParentViewController: self)
return true
}
【问题讨论】:
-
视图控制器的层次结构是什么样的?两者都有不同的导航控制器,还是相同的?
-
它们只是 2 个不同的 ViewController 没有导航控制器
-
两个不同的视图控制器在什么里面?它们必须处于某种形式或某种层次结构中,您才能同时访问它们。
-
我是 Swift 的新手,但我刚刚更新了我的代码,基本上它们是通过一个 SubView 连接的,当你第一次点击 SearchBar 时就会出现。
标签: ios swift swift3 uisearchbar