How to calculate string in text field by Xcode 8.3.3 - xcode

I want a solution in my problem.
I have text field in Xcode and I wanna Xcode calculate string thats user input as:
var x = 1
var y = 2
like this
I wanna if the user input xy inside text field, the Xcode calculate like: 1+2
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet var label1: UILabel!
#IBOutlet var label2: UILabel!
#IBOutlet var label3: UILabel!
#IBOutlet var label4: UILabel!
#IBOutlet var tex1: UITextField!
#IBOutlet var tex2: UITextField!
override function viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tex1.delegate = self
tex2.delegate = self
}
override function didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
function textFieldShouldReturn(_ textField: UITextField) -> Bool{
tex1.resignFirstResponder()
tex2.resignFirstResponder()
return true
}
#IBAction function close(_ sender: UIButton) {
tex1.resignFirstResponder()
tex2.resignFirstResponder()
}
#IBAction function pushAction(_ sender: UIButton) {
label4.text = String(Int(tex1.text)+Int(tex2.text))
}
}

var temp = 0
var prevCount = -1
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
var txtAfterUpdate:NSString = textField.text! as NSString
txtAfterUpdate = txtAfterUpdate.replacingCharacters(in: range, with: string).trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) as NSString
let newString:String! = String(txtAfterUpdate)
if(prevCount > newString.characters.count - 1){
if(newString.characters.count - 1 != -1){
self.enterAmount = self.enterAmount - Double(textField.text![(textField.text?.characters.count)! - 1])!
}else{
self.enterAmount = 0
}
}else{
self.enterAmount = Double(newString[newString.characters.count - 1])! + self.enterAmount
}
print("YOUR TOTAL \(self.enterAmount)")
prevCount = newString.characters.count - 1
return true
}
extension String{
subscript(i: Int) -> String {
guard i >= 0 && i < characters.count else { return "" }
return String(self[index(startIndex, offsetBy: i)])
}
subscript(range: Range<Int>) -> String {
let lowerIndex = index(startIndex, offsetBy: max(0,range.lowerBound), limitedBy: endIndex) ?? endIndex
return substring(with: lowerIndex..<(index(lowerIndex, offsetBy: range.upperBound - range.lowerBound, limitedBy: endIndex) ?? endIndex))
}
subscript(range: ClosedRange<Int>) -> String {
let lowerIndex = index(startIndex, offsetBy: max(0,range.lowerBound), limitedBy: endIndex) ?? endIndex
return substring(with: lowerIndex..<(index(lowerIndex, offsetBy: range.upperBound - range.lowerBound + 1, limitedBy: endIndex) ?? endIndex))
}
}

you can use like this
label4.text = "\(((tex1.text?.characters.count)! + (tex2.text?.characters.count)!))"

Related

GeoTag Images from image picker swift 3

I want to get geotag location from image which is selected from image picker. I am using this code
if picker.sourceType == UIImagePickerControllerSourceType.PhotoLibrary
{
if let currentLat = pickedLat as CLLocationDegrees?
{
self.latitude = pickedLat!
self.longitude = pickedLong!
}
else
{
var library = ALAssetsLibrary()
library.enumerateGroupsWithTypes(ALAssetsGroupAll, usingBlock: { (group, stop) -> Void in
if (group != nil) {
println("Group is not nil")
println(group.valueForProperty(ALAssetsGroupPropertyName))
group.enumerateAssetsUsingBlock { (asset, index, stop) in
if asset != nil
{
if let location: CLLocation = asset.valueForProperty(ALAssetPropertyLocation) as CLLocation!
{ let lat = location.coordinate.latitude
let long = location.coordinate.longitude
self.latitude = lat
self.longitude = lat
println(lat)
println(long)
}
}
}
} else
{
println("The group is empty!")
}
})
{ (error) -> Void in
println("problem loading albums: \(error)")
}
}
}
i want to know to covert this code in swift 3 .I am new in coding with swift 3 .It will be very helpful
After hours of searching i got my ans
import UIKit
import Photos
class ViewController: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var locationLabel: UILabel!
#IBOutlet weak var timeLabel: UILabel!
#IBOutlet weak var logi: UILabel!
#IBOutlet weak var lati: UILabel!
var lat = String()
var log = String()
var location = String()
var timeTaken = "Not Known"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func imagegeo(_ sender: Any) {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = .photoLibrary
imagePicker.delegate = self
present(imagePicker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
var chosenImage:UIImage?
if let URL = info[UIImagePickerControllerReferenceURL] as? URL {
print("We got the URL as \(URL)")
let opts = PHFetchOptions()
opts.fetchLimit = 1
let assets = PHAsset.fetchAssets(withALAssetURLs: [URL], options: opts)
print(assets)
for assetIndex in 0..<assets.count {
let asset = assets[assetIndex]
location = String(describing: asset.location)
log = String(describing: asset.location?.coordinate.longitude)
lat = String(describing: asset.location?.coordinate.latitude)
timeTaken = (asset.creationDate?.description)!
print(log)
print(location)
print(lat)
}
}
if let editedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
chosenImage = editedImage
} else if let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
chosenImage = selectedImage
}
dismiss(animated: true) {
DispatchQueue.main.async {
self.imageView.image = chosenImage
self.timeLabel.text = self.timeTaken
self.locationLabel.text = self.location
self.lati.text = self.lat
self.logi.text = self.log
}
}
}
}

Why pushViewController doesn't work in UIPageViewController?

I use uipageViewController for sliding pages. Each page has own ViewController:ContentViewController. In one of page I have button. When user click on this button it should go to another ViewController (let say home page). When I click on the button it change state, but redirection doesn't work. It seems that smth wrong with pushViewController?
Here is my code ::
class ViewController: UIViewController, UIPageViewControllerDataSource {
var pageViewController : UIPageViewController!
var pageTitles : NSArray!
var pageImages : NSArray!
let controllers = ["FirstViewController","SecondViewController"]
#IBOutlet weak var restartButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.pageTitles = NSArray(objects: "Explore", "Today Widget")
self.pageImages = NSArray(objects: "page1","page2")
self.pageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PageViewController")as! UIPageViewController
self.pageViewController.dataSource = self
var startVC = self.viewControllerAtIndex(0)as ContentViewController
var viewControllers = NSArray(object: startVC)
self.pageViewController.setViewControllers(viewControllers as! [UIViewController], direction: .Forward, animated: true, completion: nil)
self.pageViewController.view.frame = CGRectMake(0,40,self.view.frame.width,self.view.frame.height - 60)
self.addChildViewController(self.pageViewController)
self.view.addSubview(self.pageViewController.view)
self.pageViewController.didMoveToParentViewController(self)
self.view.backgroundColor = UIColor(red: (25/255.0), green: (127/255.0), blue: (216/255.0), alpha: 1.0)
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func restartAction(sender: AnyObject) {
var startVC = self.viewControllerAtIndex(0)as ContentViewController
var viewControllers = NSArray (object: startVC)
self.pageViewController.setViewControllers(viewControllers as! [UIViewController], direction: .Forward, animated: true, completion: nil)
}
func viewControllerAtIndex(index : Int)->ContentViewController
{
if (self.pageTitles.count == 0) || (index >= self.pageTitles.count){
return ContentViewController();
}
var vc:ContentViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ContentViewController")as! ContentViewController
vc = self.storyboard?.instantiateViewControllerWithIdentifier(controllers[index])as! ContentViewController
vc.pageIndex = index
return vc;
}
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
var vc = viewController as! ContentViewController
var index = vc.pageIndex as Int
if (index == 0 || index == NSNotFound){
return nil
}
index--
return self.viewControllerAtIndex(index);
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
var vc = viewController as! ContentViewController
var index = vc.pageIndex as Int
if (index == NSNotFound){
return nil
}
index++
if (index == self.pageTitles.count){
return nil
}
return self.viewControllerAtIndex(index)
}
func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
return self.pageTitles.count
}
func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int {
return 0
}
}
#IBAction func secondViewController(sender: AnyObject) {
let next = self.storyboard?.instantiateViewControllerWithIdentifier("ThirdViewController") as? ThirdViewController
navigationController?.pushViewController(next!,animated: true)
}

how do to get an image from one viewController to the next like a global

I have just a camera on my CameraController. I want the picture from my CameraContoller to go to my ComposeViewController inside of the image View in the ComposeViewController. so basically I need it so the the picture taken transfers to the other view controller once taken. There are 2 separate view controllers below in the code.
Code:
import UIKit
import AVFoundation
class CameraController : UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate{
var captureSession : AVCaptureSession?
var stillImageOutput : AVCaptureStillImageOutput?
var previewLayer : AVCaptureVideoPreviewLayer?
#IBOutlet var cameraView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
previewLayer?.frame = cameraView.bounds
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
captureSession = AVCaptureSession()
captureSession?.sessionPreset = AVCaptureSessionPreset1920x1080
var backCamera = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
var error : NSError?
var input = AVCaptureDeviceInput(device: backCamera, error: &error)
if (error == nil && captureSession?.canAddInput(input) != nil){
captureSession?.addInput(input)
stillImageOutput = AVCaptureStillImageOutput()
stillImageOutput?.outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG]
if (captureSession?.canAddOutput(stillImageOutput) != nil){
captureSession?.addOutput(stillImageOutput)
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect
previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.Portrait
cameraView.layer.addSublayer(previewLayer)
captureSession?.startRunning()
}
}
}
#IBOutlet var tempImageView: UIImageView!
func didPressTakePhoto(){
if let videoConnection = stillImageOutput?.connectionWithMediaType(AVMediaTypeVideo){
videoConnection.videoOrientation = AVCaptureVideoOrientation.Portrait
stillImageOutput?.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: {
(sampleBuffer, error) in
if sampleBuffer != nil {
var imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
var dataProvider = CGDataProviderCreateWithCFData(imageData)
var cgImageRef = CGImageCreateWithJPEGDataProvider(dataProvider, nil, true, kCGRenderingIntentDefault)
var image = UIImage(CGImage: cgImageRef, scale: 1.0, orientation: UIImageOrientation.Right)
self.tempImageView.image = image
self.tempImageView.hidden = false
}
})
}
}
var didTakePhoto = Bool()
func didPressTakeAnother(){
if didTakePhoto == true{
tempImageView.hidden = true
didTakePhoto = false
}
else{
captureSession?.startRunning()
didTakePhoto = true
didPressTakePhoto()
}
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
didPressTakeAnother()
}
}
//-----Below is my Next View Controller where i want the image from the above view controller to show up--------------------------------------- --------------------------------------------------------------------------- --------------
class ComposeViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextViewDelegate {
#IBOutlet weak var captionTextView: UITextView!
#IBOutlet weak var previewImage: UIImageView!
let tap = UITapGestureRecognizer()
override func viewDidLoad() {
super.viewDidLoad()
var swipe: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "GotoProfile")
swipe.direction = UISwipeGestureRecognizerDirection.Right
self.view.addGestureRecognizer(swipe)
tap.numberOfTapsRequired = 2
tap.addTarget(self, action: "GoBack")
view.userInteractionEnabled = true
view.addGestureRecognizer(tap)
captionTextView.delegate = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func CaptonField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if range.length + range.location > count(captionTextView.text){
return false
}
let NewLength = count(captionTextView.text) + count(string) - range.length
return NewLength <= 35
}
#IBAction func chooseImageFromCamera() {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .Camera
presentViewController(picker,animated: true, completion:nil)
}
func GotoProfile(){
self.performSegueWithIdentifier("NewCameraViewFromComposeSegue", sender: nil)
}
func GoBack(){
self.performSegueWithIdentifier("GoBackFromCamerasegue", sender: nil)
}
#IBAction func addImageTapped(sender: AnyObject) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
imagePicker.mediaTypes = UIImagePickerController.availableMediaTypesForSourceType(.PhotoLibrary)!
imagePicker.allowsEditing = false
self.presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
self.previewImage.image = image
self.dismissViewControllerAnimated(true, completion: nil)
}
func textViewShouldEndEditing(textView: UITextView) -> Bool {
captionTextView.resignFirstResponder()
return true;
}
#IBAction func composeTapped(sender: AnyObject) {
let date = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
let localDate = dateFormatter.stringFromDate(date)
let imageToBeUploaded = self.previewImage.image
let imageData = UIImagePNGRepresentation(imageToBeUploaded)
let file: PFFile = PFFile(data: imageData)
let fileCaption: String = self.captionTextView.text
var photoToUpload = PFObject(className: "Posts")
photoToUpload["Image"] = file
photoToUpload["Caption"] = fileCaption
photoToUpload["addedBy"] = PFUser.currentUser()?.username
photoToUpload["date"] = localDate
photoToUpload.save()
println("Successfully Posted.")
let vc: AnyObject? = self.storyboard?.instantiateViewControllerWithIdentifier("NavigationController")
self.presentViewController(vc as! UIViewController, animated: true, completion: nil)
}
}
Are you using a segue to get from the first to the second ViewController ?
If so you can access the second VC in in your first VC in the prepareForSegue function :
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ComposeVCIdentifier" {
let composeViewController = segue.destinationViewController as! ComposeViewController
composeViewController.someVariable = myPicture
}
}

Terminator found in the middle of a basic block

All went fine until my project won't compile.I see those things on two of my files.
Terminator found in the middle of a basic block!
label %50
LLVM ERROR: Broken function found, compilation aborted!
Terminator found in the middle of a basic block!
label %71
LLVM ERROR: Broken function found, compilation aborted!
And the error the compiler give
Command /Applications/Xcode-beta 2.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1
I tried solving it, but no success.
Older version of the files compile.
The problem is in the files,but what is the terminator?
Where is the problem?
EDIT
Here is some code, the classes are big
LandscapeViewController
import UIKit
class LandscapeViewController: UIViewController,UIScrollViewDelegate {
// MARK: Properties
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var pageControl: UIPageControl!
var search: Search!
private var firstTime = true
private var downloadTasks = [NSURLSessionDownloadTask]()
#IBAction func pageChange(sender: UIPageControl){
UIView.animateWithDuration(0.3, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
self.scrollView.contentOffset = CGPoint(x: self.scrollView.bounds.size.width * CGFloat(sender.currentPage), y: 0)
}, completion: nil )
}
// MARK: Buttons
private func tileButtons(searchResults: [SearchResult]){
var columnsPerPage = 5
var rowsPerPage = 3
var itemWidth: CGFloat = 96
var itemHeight: CGFloat = 88
var marginX: CGFloat = 0
var marginY: CGFloat = 20
let buttonWidth: CGFloat = 82
let buttonHeight: CGFloat = 82
let scrollViewWidth = scrollView.bounds.size.width
switch scrollViewWidth{
case 568:
columnsPerPage = 6
itemWidth = 94
marginX = 2
case 667:
columnsPerPage = 7
itemWidth = 95
itemHeight = 98
marginX = 1
marginY = 29
case 736:
columnsPerPage = 8
rowsPerPage = 4
itemWidth = 92
default:
break
}
let paddingHorz = (itemWidth - buttonWidth)/2
let paddingVert = (itemHeight - buttonHeight)/2
var row = 0
var column = 0
var x = marginX
for (index,searchResult) in searchResults.enumerate(){
let button = UIButton(type: .Custom)
button.setBackgroundImage(UIImage(named: "LandscapeButton"), forState: .Normal)
downloadImageForSearchResult(searchResult, andPlaceOnButton: button)
button.tag = 2000 + index
button.addTarget(self, action: Selector("buttonPressed:"), forControlEvents: .TouchUpInside)
button.backgroundColor = UIColor.whiteColor()
button.frame = CGRect(x: x + paddingHorz, y: marginY + CGFloat(row)*itemHeight + paddingVert, width: buttonWidth, height: buttonHeight)
scrollView.addSubview(button)
++row
if row == rowsPerPage{
row = 0
++column
x += itemWidth
if column == columnsPerPage{
column = 0
x += marginX * 2
}
}
}
let buttonsPerPage = columnsPerPage * rowsPerPage
let numPages = 1 + (searchResults.count - 1) / buttonsPerPage
pageControl.numberOfPages = numPages
pageControl.currentPage = 0
scrollView.contentSize = CGSize(width: CGFloat(numPages) * scrollViewWidth, height: scrollView.bounds.size.height)
}
private func downloadImageForSearchResult(searchResult: SearchResult,andPlaceOnButton button: UIButton){
if let url = NSURL(string: searchResult.artworkURL60){
let session = NSURLSession.sharedSession()
let downloadTask = session.downloadTaskWithURL(url,completionHandler: { [weak button] url, response, error in
if error == nil && url != nil{
if let data = NSData(contentsOfURL: url!){
if let image = UIImage(data: data){
let resizedImage = image.resizedImageWithBounds(CGSize(width: 60, height: 60))
dispatch_async(dispatch_get_main_queue()){
if let button = button{
button.setImage(resizedImage, forState: .Normal)
}
}
}
}
}
})
downloadTasks.append(downloadTask!)
downloadTask?.resume()
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowDetail"{
switch search.state{
case .Results(let list):
let destinationViewController = segue.destinationViewController as! DetailViewController
let searchResult = list[sender!.tag - 2000]
destinationViewController.searchResult = searchResult
default:
break
}
}
}
func buttonPressed(sender: UIButton){
performSegueWithIdentifier("ShowDetail", sender: sender)
}
// MARK: UIScrollViewDelegate
func scrollViewDidScroll(scrollView: UIScrollView) {
let width = scrollView.bounds.size.width
let currentPage = Int((scrollView.contentOffset.x + width/2) / width)
pageControl.currentPage = currentPage
}
// MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
pageControl.numberOfPages = 0
scrollView.backgroundColor = UIColor(patternImage: UIImage(named: "LandscapeBackground")!)
view.removeConstraints(view.constraints)
view.translatesAutoresizingMaskIntoConstraints = true
pageControl.removeConstraints(pageControl.constraints)
pageControl.translatesAutoresizingMaskIntoConstraints = true
scrollView.removeConstraints(scrollView.constraints)
scrollView.translatesAutoresizingMaskIntoConstraints = true
// Do any additional setup after loading the view.
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
scrollView.frame = view.bounds
pageControl.frame = CGRect(x: 0, y: view.frame.size.height - pageControl.frame.size.height, width: view.frame.size.width, height: pageControl.frame.size.height)
if firstTime{
firstTime = false
switch search.state{
case .NotSearchedYet:
break
case .Loading:
showSpinner()
case .NoResults:
showNothingFoundLabel()
case.Results(let list):
tileButtons(list)
}
}
}
private func showNothingFoundLabel() {
let label = UILabel(frame: CGRect.zeroRect)
label.text = "Nothing Found"
label.backgroundColor = UIColor.clearColor()
label.textColor = UIColor.whiteColor()
label.sizeToFit()
var rect = label.frame
rect.size.width = ceil(rect.size.width/2) * 2
rect.size.height = ceil(rect.size.height/2) * 2
label.frame = rect
label.center = CGPoint(x: CGRectGetMidX(scrollView.bounds), y: CGRectGetMidY(scrollView.bounds))
view.addSubview(label)
}
private func showSpinner(){
let spinner = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge)
spinner.center = CGPoint(x: CGRectGetMidX(scrollView.bounds) + 0.5, y: CGRectGetMidY(scrollView.bounds) + 0.5)
spinner.tag = 1000
view.addSubview(spinner)
spinner.startAnimating()
}
func searchResultsRecived(){
hideSpinner()
switch search.state {
case .NotSearchedYet, .Loading:
break
case .NoResults:
showNothingFoundLabel()
case .Results(let list):
tileButtons(list)
}
}
private func hideSpinner(){
view.viewWithTag(1000)?.removeFromSuperview()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit{
print("deinit \(self)")
for task in downloadTasks{
task.cancel()
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
SearchViewController
import UIKit
class SearchViewController: UIViewController,UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate {
private struct TableViewCellIdentifier {
static let searchResultCell = "SearchResultCell"
static let nothingFoundCell = "NothingFoundCell"
static let loadingCell = "LoadingCell"
}
// MARK: LandscapeViewController
override func willTransitionToTraitCollection(newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.willTransitionToTraitCollection(newCollection, withTransitionCoordinator: coordinator)
switch newCollection.verticalSizeClass{
case .Compact:
showLandscapeViewWithCoordinator(coordinator)
case .Regular,.Unspecified:
hideLandscapeViewWithCoordinator(coordinator)
}
}
private func showLandscapeViewWithCoordinator(coordinator: UIViewControllerTransitionCoordinator){
precondition(landscapeViewController == nil)
landscapeViewController = storyboard?.instantiateViewControllerWithIdentifier("LandscapeViewController") as? LandscapeViewController
if let controller = landscapeViewController{
controller.search = search
controller.view.frame = view.frame
controller.view.alpha = 0
view.addSubview(controller.view)
addChildViewController(controller)
coordinator.animateAlongsideTransition({ _ in
if self.presentedViewController != nil{
self.dismissViewControllerAnimated(true, completion: nil)
}
self.searchBar.resignFirstResponder()
controller.view.alpha = 1
}, completion: { _ in
controller.didMoveToParentViewController(self)
})
}
}
private func hideLandscapeViewWithCoordinator(coordinator: UIViewControllerTransitionCoordinator){
if let controller = landscapeViewController{
controller.willMoveToParentViewController(nil)
coordinator.animateAlongsideTransition({ _ in
controller.view.alpha = 0
}, completion: { _ in
if self.presentedViewController != nil {
self.dismissViewControllerAnimated(true, completion: nil)
}
controller.view.removeFromSuperview()
controller.removeFromParentViewController()
self.landscapeViewController = nil
})
}
}
private func showNetworkError(){
let alert = UIAlertController(title: "Whoops...", message: "There was an error reading from the iTunes Store. Please try again.", preferredStyle: .Alert)
let action = UIAlertAction(title: "OK", style: .Default, handler: nil)
alert.addAction(action)
presentViewController(alert, animated: true, completion: nil)
}
// MARK: Detail ViewController
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowDetail" {
switch search.state{
case . Results(let list):
let indexPath = sender as! NSIndexPath
let searchResult = list[indexPath.row]
let detailViewController = segue.destinationViewController as! DetailViewController
detailViewController.searchResult = searchResult
default:
break
}
}
}
// MARK: Properties
#IBOutlet weak var searchBar: UISearchBar!
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var segmentedControl: UISegmentedControl!
let search = Search()
private var landscapeViewController: LandscapeViewController?
// MARK: Methodes
#IBAction func segmentedControl(sender: UISegmentedControl) {
performSearch()
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.contentInset = UIEdgeInsets(top: 108, left: 0, bottom: 0, right: 0)
tableView.rowHeight = 80
searchBar.becomeFirstResponder()
configureNib(nibName: TableViewCellIdentifier.searchResultCell)
configureNib(nibName: TableViewCellIdentifier.nothingFoundCell)
configureNib(nibName: TableViewCellIdentifier.loadingCell)
}
private func configureNib(nibName nibName: String){
let cellNib = UINib(nibName: nibName, bundle: nil)
tableView.registerNib(cellNib, forCellReuseIdentifier: nibName)
}
// MARK: UISearchBarDelegate
func searchBarSearchButtonClicked(searchBar: UISearchBar){
performSearch()
}
private func performSearch() {
if let category = Search.Category(rawValue: segmentedControl.selectedSegmentIndex){
search.performSearchForText(searchBar.text!, category: category){
success in
if !success{
self.showNetworkError()
}
if let controller = self.landscapeViewController{
controller.searchResultsRecived()
}
self.tableView.reloadData()
}
tableView.reloadData()
searchBar.resignFirstResponder()
}
}
func positionForBar(bar: UIBarPositioning) -> UIBarPosition {
return .TopAttached
}
// MARK: TableView
// MARK: - UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch search.state{
case .NotSearchedYet:
return 0
case .Loading,.NoResults:
return 1
case .Results(let list):
return list.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch search.state{
case .NotSearchedYet:
fatalError("Should never get here")
case .Loading:
let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifier.loadingCell, forIndexPath: indexPath)
let spinner = cell.viewWithTag(100) as! UIActivityIndicatorView
spinner.startAnimating()
return cell
case .NoResults:
return tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifier.nothingFoundCell, forIndexPath: indexPath)
case .Results(let list):
let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifier.searchResultCell, forIndexPath: indexPath) as! SearchResultCell
let searchResult = list[indexPath.row]
cell.configureForSearchResult(searchResult)
return cell
}
}
// MARK: UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
performSegueWithIdentifier("ShowDetail", sender: indexPath)
}
func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
switch search.state{
case .NotSearchedYet,.NoResults,.Loading:
return nil
case .Results:
return indexPath
}
}
}
This is a bug in the Swift compiler, you'll want to file a radar with Apple to report this. There's nothing you can do about it otherwise.
I had this error because I had a switch of an enum with a case that contain an Array payload (don't ask me why, I don't know).
I think the enum is the search state inside the tableView:cellForRowAtIndexPath: method of SearchViewController and the prepareForSegue: method of LandscapeViewController (the .Result case contain a list).
In my case, changing the payload to a Set instead of an Array worked. (as a workaroud until it's fixed)

PreparetoSegue Button Command to Another ViewController Swift

How do I preparetoSegue a button command to another ViewController? It seem my calculateButton is giving me an error code.
MainViewController
if (segue.identifier == "toCalculate") {
let destViewController : CalcualteViewController = segue.destinationViewController as CalcualteViewController
destViewController.calculateButton(sender: UIButton) {
let dataone = data1.text.toInt() ?? 0
let datatwo = data2.text.toInt() ?? 0
let answercalculation = dataone * datatwo
answer.text = "\(answercalculation)" + " psi"
}
CalculateViewController
class CalcualteViewController: UIViewController {
#IBOutlet weak var textlabel: UILabel!
#IBOutlet var answer: UITextField!
#IBOutlet var data1: UITextField!
#IBOutlet var data2: UITextField!
#IBAction func calculateButton(sender: AnyObject) {
}
destViewController.calculateButton is a method of CalculateViewController. You have a closure hanging off the end of it when it doesn't accept any arguments accept sender: AnyObject. Move your logic into the CalculateViewController.
#IBAction func calculateButton(sender: AnyObject) {
let dataone = data1.text.toInt() ?? 0
let datatwo = data2.text.toInt() ?? 0
let answercalculation = dataone * datatwo
answer.text = "\(answercalculation)" + " psi"
}
If you want to share the code across multiple controllers you could create an instance variable called var calculateButtonAction: ((UIButton) -> ())? and then set it in prepareForSegue:
destinationViewController.calculateButtonAction = { (sender) in
let dataone = destinationViewController.data1.text.toInt() ?? 0
let datatwo = destinationViewController.data2.text.toInt() ?? 0
let answercalculation = dataone * datatwo
destinationViewController.answer.text = "\(answercalculation)" + " psi"
}
And then call it from CalculatorViewController:
#IBAction func calculateButton(sender: AnyObject) {
if let action = calculateButtonAction {
action(sender)
}
}
Better yet, create a BaseCalculatorViewController and subclass it for your controllers so you can have your subclasses inherit calculateButton.

Resources