我有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作为SubView的方式
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
}
最佳答案
尝试这个:
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
Popup.textFromSearch = mySearch.text
self.view.addSubview(Popup.view)
Popup.didMove(toParentViewController: self)
return true
}
并在IBOutlet之后的Controller 2中添加var:
var textFromSearch = ""