Я пытаюсь добавить возможности поиска в проект на основе карты, над которым я работаю быстро на XCode 6. Я добавил SearchDisplayController в свой основной контроллер представления, который содержит карту , Я создал класс MapSearchDisplayController, который реализует необходимые методы. Я также изменил свойство Custom Class объекта SearchDisplayController на MapSearchDisplayController в раскадровке.ios - IBOutlet класс init не вызывается, а члены - nil
В раскадровке я перетащил SearchDisplayController на свой главный контроллер представления, чтобы создать IBOutlet. Мой главный viewDidLoad для основного контроллера представления выглядит следующим образом:
class ViewController: UIViewController, CCHMapClusterControllerDelegate, MKMapViewDelegate, ADBannerViewDelegate {
@IBOutlet weak var mapSearchDisplayController1: MapSearchDisplayController!
@IBOutlet var mapSearchDisplayController: MapSearchDisplayController!
@IBOutlet weak var banner: ADBannerView!
@IBOutlet weak var mMap: MKMapView!
var clusterController:CCHMapClusterController?
let mMaxZoomLevelForClustering : Double = 13
let mMinUniqueLocationsForClustering : UInt = 1
var formatter = NSNumberFormatter()
var databasePath = NSString()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
banner.delegate = self
// Add button to navbar
var filterButton : UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Organize, target: self, action: nil)
self.navigationItem.leftBarButtonItem = filterButton
var aboutButton : UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "aboutAction")
var searchButton : UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Search, target: self, action: "searchAction")
var rButtons : [UIBarButtonItem] = [aboutButton, searchButton]
self.navigationItem.rightBarButtonItems = rButtons
// Deal with Search Display Controller
self.mapSearchDisplayController.delegate = self.mapSearchDisplayController;
self.mapSearchDisplayController.searchResultsDataSource = self.mapSearchDisplayController;
self.mapSearchDisplayController.searchResultsDelegate = self.mapSearchDisplayController;
self.mapSearchDisplayController.searchBar.placeholder = "Search Destination";
self.mapSearchDisplayController.searchResultsTableView.delegate = self.mapSearchDisplayController
self.mapSearchDisplayController.searchResultsTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
Выпуск 1: я должен был добавить дополнительный mapSearchDisplayController - иначе мой mapSearchDisplayController был равен нулю, и у меня было исключение, когда я пытался в используй это. Теперь, когда у меня есть дополнительная переменная mapSearchDisplayController (она объявлена, но никогда не используется), она не бросает исключения и работает некоторая функциональность. Пытался добавить/удалить слабый, bt это не имело никакого значения. Я не могу понять, что я пропустил, что ведет к такому поведению.
Isse 2: Еще большая проблема, что у меня есть, в том, что переменный экземпляре mapSearchDisplayController, который обрабатывает функцию, связанные с поиском, является нулевым, его метод инициализации является не вызывается, но функциональность в работе методов делегата , Таким образом, переменная data1 равна нулю, несмотря на то, что она инициализируется жестко закодированным массивом строк. То же самое касается всех других участников, включая googleAPIKey, который является константой. Если shouldReloadTableForSearchString снова установил data1 data1 = ["1111", "222", "ZAAAA"]
, то он будет инициализирован, но если я присвою data1 значение, которое я получаю как результат поиска, оно будет потеряно. Я бы понял, был ли весь объект нулевым, но методы вызываются и работают, это просто переменные экземпляра и init, которые не работают. Код ниже:
class MapSearchDisplayController: UISearchDisplayController, UISearchDisplayDelegate, UITableViewDataSource, UITableViewDelegate, LPGoogleFunctionsDelegate
{
var data1 : [String]! = ["1111", "222", "ZAAAA"]
var googleFunctions : LPGoogleFunctions? = LPGoogleFunctions()
let googleAPIKey = "myKey"
//MARK: UITableViewDelegate
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
println("In numberOfRowsInSection - \(data1.count)")
return self.data1.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
println("In cellForRowAtIndexPath")
var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as? UITableViewCell
if !(cell != nil) {
println("new cellForRow")
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
}
// Get the corresponding candy from our candies array
let candy = self.data1[indexPath.row]
// Configure the cell
cell!.textLabel.text = candy
cell!.detailTextLabel?.text = "Cell Details"
return cell!
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
// Dismiss search display controller
self.active = false;
// Force selected annotation to be on map
}
func tableView(tableView: UITableView, numberOfSectionsInTableView indexPath: NSIndexPath) -> Int{
println("numberOfSectionsInTableView")
return 1
}
//MARK: Search methods
func filterContentForSearchText (searchText: String) {
println(searchText)
}
func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchString searchString: String!) -> Bool {
var length : Int32 = Int32(countElements(searchString))
if (countElements(searchString) < 3) {
println("Short searchString. Not enough info")
return false
}
data1 = []
if (googleFunctions == nil)
{
googleFunctions = LPGoogleFunctions()
googleFunctions!.sensor = false
googleFunctions!.delegate = self
googleFunctions!.googleAPIBrowserKey = "myKey"
}
println(googleFunctions?.googleAPIBrowserKey)
googleFunctions?.loadPlacesAutocompleteWithDetailsForInput(searchString, offset: length, radius: 0, location: nil, placeType: LPGooglePlaceTypeGeocode, countryRestriction: nil, successfulBlock: {(pd : [AnyObject]!) in
println("--------------GOOGLE search success")
for place in pd{
var pl = place as LPPlaceDetails
self.data1.append(pl.name)
println(pl.name)
}
}
, failureBlock: {(status : LPGoogleStatus) in
println("---- GOOGLE failed")
})
//data1 = ["1111", "222", "ZAAAA"]
return true
}
func searchDisplayControllerWillBeginSearch(controller: UISearchDisplayController!){
controller.searchBar.showsCancelButton = true
}
func searchDisplayControllerWillEndSearch(controller: UISearchDisplayController!){
println("searchDisplayControllerWillEndSearch")
}
//MARK: LPGogleFunctions methods
override init() {
println("Initializing GoogleFunctions")
if (googleFunctions == nil){
googleFunctions = LPGoogleFunctions()
}
data1 = []
super.init()
googleFunctions!.sensor = false
googleFunctions!.delegate = self
googleFunctions!.googleAPIBrowserKey = "myKey"
}
}
Любая помощь была бы принята с благодарностью.
Тогда почему объектив-c-тэг стоит? – Cheese
слабый var mapSearchDisplayController1: MapSearchDisplayController! Здесь я думаю, что у вас было ноль, потому что у вас слабое повторение, попробуйте использовать сильные. – Cheese
Извините, какие теги вы имели в виду? – asda28