📜 ⬆️ ⬇️

"Mouse Programming" in Xcode 6 for Swift

Hi, Habrahabr!

Due to the recent need, I had to write under iOS, and I noticed a strong lack of guides in Russian even for elementary actions like “attach some action to a button’s press”, “read data from a text window”. Article for novice developers under iOS, I ask such under kat.

So, for starters to work out examples

Let's create the project SingleView Application


If you are able to create, then this stage can be skipped
  1. Choose a project type
  2. Choose a name
  3. Done, you can proceed



Further complicate our application


  1. Change the controller class of our first View to MainViewController
    Like this
    Before:
    ')
    After (change the name of the class and file):

    Before:

    After (CustomClass on the top right we change to a new one)):

  2. Add a second View and ViewController for it (let's call it SpecialViewController)
    Like this
    Hover the mouse over the desired controller type (ViewController) and drag it to the interface tab (Drag-n-Drop), then create a class for our new SpecialViewController controller (the base code is standard and similar to the main controller code at this stage) in the new file called SpecialViewController.swift. Then we select our controller in the visual editor and in its properties in the CustomClass tab in the Class field we select our newly created controller class from the list.




So, we now have two windows, one of which simply cannot be accessed by the user.

Let's go to programming with the mouse



1. Add items to the visual editor.

This is the easiest part, done as elsewhere.
We set the Placeholder property to the text field; it allows to display an “invitation for input”, which is visible only until no text is entered. But the properties will not be much spread in this article, so as not to overload.


2. Add our elements to the controller class, to work with them directly

First you need to choose the icon at the top, we need it to simultaneously see the controller in the visual editor and the class code of the same controller. Then we simply “drag” the controller element we need with the right mouse button in the visual half onto its code. You will be offered an arbitrary variable name, in which the element is now available for all functions of the controller.


3. Add event handling for window elements

This requires little preparation. First click the PC on the desired item, you get this window:

The list of events here will not describe, they, IMHO, are self-evident. Select the one you need and drag it to the code with the left mouse button.


4. A small example

Here we press the button to change the text of the Label to the user entered. With a demonstration of work on the simulator for iPhone 6


As the most attentive readers might have noticed, our editor swears at the impossibility of getting into SpecialView. And he is right! To solve this problem through a visual editor, there is such a thing as Segue. Thanks to them, we can clearly show where from where the user can go.

Transitions between windows



1. The simplest option

The easiest option is an unconditional transition. To do this, add the “Go” button to our project, click on it with the RMB and drag the appeared line to the View to which we want to get the transition (SpecialView in our case). We will receive a request about the type of Segue, select show there - you can experiment with the rest. Similarly, add a button to the SpecialView back, and attach to it the transition to the MainView.

Here's what it looks like in a running application.


As you can see, the simplest transitions can be created without writing a single line of code. But, of course, unconditional transitions are not always enough.

2. Add a conditional transition

The easiest way to do this is to call our transition through the code. But there is no code in it. Yes, and at the press of a button, it will still work, but this would not be desirable. The way out is quite simple: we delete the old version of the transition, and we are leading the new not from our button, but from the yellow circle of the ViewController itself, let's call our transition MainToSpecial

So, let us want to let the user in SpecialView only if the input field and Label contain the same text.
To do this, we need to create a push event for the button in the controller, and check this condition in it. If it is executed, perform the transition using this code:
self.performSegueWithIdentifier("MainToSpecial", sender: self)// MainToSpecial       

This code is added like this


Checking ...
Everything is working


As you can see, it lets on SpecialView only with the same values ​​in the fields, but back - in any case, what we need.
At this point, you can finish, but finally I’ll show you an asynchronous check of transition conditions, since IMHO it is no less important.

3. Asynchronous transition with checking conditions on the server

In general, there are not too many differences from the synchronous version:
  1. The condition check does not happen instantly and cannot be found directly in the button click handler.
  2. We need to somehow show the user what he is waiting for.
  3. Have to use callbacks

First, all application logic that does not have an interface should be in separate classes, so let's create the Server class in the Server.swift file with a single function (the code is not very good, but I don’t want to complicate the example):
Hidden text
 import UIKit let server=Server() class Server { private let apiURL="http://worldteam-m.com/test.php?" func tryCheck(data:String,callback:(NSDictionary)->Void) { let request=(self.apiURL+data) let encoded = request.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) var url: NSURL = NSURL( string: encoded!)! var session = NSURLSession.sharedSession() var task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in println("Task completed") if((error) != nil) { println(error.localizedDescription) } var err: NSError? var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary if (err? != nil) { println(error.localizedDescription) } dispatch_async(dispatch_get_main_queue(), { callback(jsonResult) }) }) task.resume() } } 


The server is not specified, because habraeffekt. So this part of the application you can only test with your server, or using someone else's public webAPI for testing. See UPD
In this code, we make a request, and if we receive a response, we send it to the callback passed to us from the UI.
The MainViewController code will change to this:
Hidden text
  @IBAction func MtoS(sender: AnyObject) { server.tryCheck( WhereLbl.text! + FromText.text!, callback: onResponse) } func onResponse(json:NSDictionary) { if json["code"] as String == "ok" { //,      ,    {"code":"ok"} self.performSegueWithIdentifier("MainToSpecial", sender: self)// ,   } else { self.WhereLbl.text="Forbidden!"//    } } 


And there remains one unpleasant, but important point - to show the user a delay. For this there is a special component UIActivityIndicatorView , and we immediately set the HidesWhenStopped property to it so that it is visible only during the animation, when we start an asynchronous request we turn on its animation, and when we receive the answer in our callback - we turn it off.


A lot more can be written about programming in Swift in XCode, but for now let's stop there.
I hope that the article will benefit newcomers, and maybe not only them (hehe).

UPD Added server for test asynchronous version in server class code, you can test)
Well, or upload your PHP file to your hosting and change apiURL to a link to your file.
 <?php sleep(4); if(rand()%2==0) { print json_encode(["code"=>"ok"]); } else print json_encode(["code"=>"fail"]); return; ?> 

Source: https://habr.com/ru/post/242277/


All Articles