четверг, 30 июля 2015 г.

Примитивные типы в Swift: замыкания и перечисления

1. Замыкания (closures)

Closure Expression Syntax


  • { (parameters) -> return type in
  •     statements
  • }

Пример:

  • reversed = sorted(names, { (s1: String, s2: String) -> Bool in
  • return s1 > s2
  • })


Документация: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html


2. Перечисления (Enum)

Enumeration Syntax

Синтаксис:
  1. enum SomeEnumeration {
  2. // enumeration definition goes here
  3. }
Пример:
  1. enum CompassPoint {
  2. case North
  3. case South
  4. case East
  5. case West
  6. }


Документация: 

https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Enumerations.html


среда, 29 июля 2015 г.

Добавление и удаление строк в UITableView

1. Добавление строки

Метод @IBAction связанный с кнопкой Add,  вызываемый для добавления элементов/строк в UITableView :

четверг, 23 июля 2015 г.

Swipes and shakes in swift

1. Обработка и добавление swipe-жеста
 //...
       let swipeRightRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("onSwipe:"))
        swipeRightRecognizer.direction = UISwipeGestureRecognizerDirection.Right
        self.view.addGestureRecognizer(swipeRightRecognizer)
    }
   
    func onSwipe(gesture: UIGestureRecognizer) {
        if let swipe = gesture as? UISwipeGestureRecognizer {
            switch swipe.direction {
            case UISwipeGestureRecognizerDirection.Right:
                println("right")
            default:
                break
            }
        }
    }


2.  Обработка и добавление shake-жеста

override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) {
        if motion == UIEventSubtype.MotionShake {
            println("shake")
        }
 }


пятница, 17 июля 2015 г.

Keyboard Control

Для того чтобы клавиатура исчезала при тапе на свободное место экрана необходимо добавить :

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        self.view.endEditing(true)

}

Для того чтобы клавиатура исчезала при тапе на UIButton :
@IBOutlet weak var textView: UITextView!
@IBAction func click(sender: AnyObject) {
        textView.resignFirstResponder()
}

Для того чтобы клавиатура исчезала при тапе на кнопку Return (UITextField):

// Добавляем protocol UITextFieldDelegate
class ViewController: UIViewController, UITextFieldDelegate
    @IBOutlet weak var field: UITextField// Добавляем ссылку на UITextField

    override func viewDidLoad() {
        super.viewDidLoad()
        //Устанавливаем ссылку delegate на self   
        self.field.delegate = self

    }
   
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
//...
}

вторник, 7 июля 2015 г.

Where am I App

Запускаем XCode и Создаем приложение:

Выбираем Single View Application.

Language: Swift
Devices: IPhone

Добавляем зависимости:

Для этого щелкаем по знаку + в разделе Link Binary With Libraries.

Добавляем 2 фреймворка:

CoreLocation

И MapKit





Выбираем в Project Navigator (Левое меню) Main.storyboard :

Добавляем из Object Library MapKitView:


Добавляем Delegate k ViewController правым щелчком по MapKitView вызвав меню:


Для того что бы ОС разрешила нам определять текущее местоположение устройства необходимо запросить у пользователя разрешение. В Project Manager выбираем Supporting Files -> Info.pllist
Открываем как Source Code:
Добавляем строки:
    <key>NSLocationWhenInUseUsageDescription</key>
    <string>App need to know(when it starts) your location</string>
    <key>NSLocationAlwaysUsageDescription</key>
    <string>App tracking your location to calculate your activity time</string>


 Естественно, что для настоящего приложения необходимы более убедительные объяснения.


Переходим во ViewController.swift и импортируем фреймворки:

import MapKit
import CoreLocation



Добавляем интерфейсы делегатов MKMapViewDelegate, CLLocationManagerDelegate к классу:

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

Добавляем outlet MKMapView с именем map:


@IBOutlet weak var map: MKMapView!


Исходный текст с комментариями

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var map: MKMapView!
   
    var manager = CLLocationManager() // CoreLocation manager
   
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        initializeManager() // CoreLocation manager initializations
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

   
    func initializeManager() {
        manager.delegate = self // Устанавливаем delegate
        manager.desiredAccuracy = kCLLocationAccuracyBest //Устанавливаем точность
        manager.requestWhenInUseAuthorization() // Запрашиваем разрешение на получение данных о местонахождении (1 раз)
        manager.startUpdatingLocation() // Начинаем получать данные о текущем положении
    }
   
    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { //callback вызываемый после получения данных о местоположении
//        println("locations : \(locations)") // отладка
       
        var currentLocation:CLLocation = locations[0] as! CLLocation // Получаем самые свежие данные о текущем положении
        var latitude = currentLocation.coordinate.latitude // широта
        var longitude = currentLocation.coordinate.longitude // долгота
        let speed = currentLocation.speed
        let altitude = currentLocation.altitude
        let accuracy = currentLocation.horizontalAccuracy
       
        var dict = ["latitude": latitude, "longitude": longitude]
       
        label.text = "latitude \(latitude), longitude \(longitude), altitude \(altitude), speed \(speed), accuracy \(accuracy)"
       
        setRegion(setLocation(dict)) //устанавливаем текущее местоположение на карте
    }
   
    func setLocation(dict: Dictionary<String, CLLocationDegrees>) -> CLLocationCoordinate2D{ // helper для получения location:CLLocationCoordinate2D
       
       
        var latitude:CLLocationDegrees = dict["latitude"]! // получаем широту из словаря - параметр функции
        var longitude:CLLocationDegrees = dict["longitude"]! // получаем долготу из словаря - параметр функции
       
        var location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
       
        return location
    }
   
    func setRegion(location: CLLocationCoordinate2D) {  // helper для установки текущего местоположения на карте
        var latDelta:CLLocationDegrees = 0.01 // точность при определении широты
        var lonDelta:CLLocationDegrees = 0.01 // точность при определении долготы
       
        var span:MKCoordinateSpan = MKCoordinateSpan(latitudeDelta: latDelta, longitudeDelta: lonDelta) // точность
        var region:MKCoordinateRegion = MKCoordinateRegionMake(location, span) // текущее местоположение
       
        map.setRegion(region, animated: true) // установка текущего местоположения на карте
    }
}