我正在尝试构建一个应用程序,在其中将文本输入 atextField
并获得谷歌通过其 Fetcher GooglePlaces API 提供的自动预测。我已经复制了代码并为我的应用程序进行了更改,但我无法弄清楚我做错了什么。我正在使用 Swift Xcode8 Beta 3。
请在下面查看我的代码。
import UIKit
import GooglePlaces
import GoogleMaps
class NewTripAddCitiesViewController: UIViewController {
var fetcher: GMSAutocompleteFetcher?
@IBOutlet var textView: UITextView!
@IBOutlet var placesTextField: UITextField!
@IBOutlet var addToTripLabel: UIButton!
@IBOutlet var addCitiesLabel: UILabel!
@IBAction func addPlaceToTable(_ sender: AnyObject) {
}
@IBAction func savePlaces(_ sender: AnyObject) {
}
override func viewDidLoad() {
super.viewDidLoad()
addCitiesLabel.text = "Please select which places you'd like to visit in \(tripCountry):"
addToTripLabel.setTitle("Add to \"\(tripName)\"", for: [])
self.view.backgroundColor = UIColor.white()
self.edgesForExtendedLayout = []
// Set bounds to inner-west Sydney Australia.
let neBoundsCorner = CLLocationCoordinate2D(latitude: -33.843366, longitude: 151.134002)
let swBoundsCorner = CLLocationCoordinate2D(latitude: -33.875725, longitude: 151.200349)
let bounds = GMSCoordinateBounds(coordinate: neBoundsCorner, coordinate: swBoundsCorner)
// Set up the autocomplete filter.
let filter = GMSAutocompleteFilter()
filter.type = .establishment
// Create the fetcher.
fetcher = GMSAutocompleteFetcher(bounds: bounds, filter: filter)
fetcher!.delegate = self
placesTextField = UITextField(frame: CGRect(x: 5.0, y: 0, width: self.view.bounds.size.width - 5.0, height: 44.0))
placesTextField?.autoresizingMask = .flexibleWidth
placesTextField?.addTarget(self, action: Selector(("textFieldDidChange:")), for: .editingChanged)
textView = UITextView(frame: CGRect(x: 0, y: 45.0, width: self.view.bounds.size.width, height: self.view.bounds.size.height - 45.0))
textView?.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
textView?.text = "No Results"
textView?.isEditable = false
self.view.addSubview(placesTextField!)
self.view.addSubview(textView!)
}
func textFieldDidChange(placesTextField: UITextField) {
fetcher?.sourceTextHasChanged(placesTextField.text!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension NewTripAddCitiesViewController: GMSAutocompleteFetcherDelegate {
func didAutocompleteWithPredictions(predictions: [GMSAutocompletePrediction]) {
let resultsStr = NSMutableAttributedString()
for prediction in predictions {
resultsStr.append(prediction.attributedPrimaryText)
resultsStr.append(AttributedString(string: "\n"))
}
textView?.attributedText = resultsStr
}
func didFailAutocompleteWithError(_ error: NSError) {
textView?.text = error.localizedDescription
}
}