カテゴリー
SugiBlog Webデザイナー・プログラマーのためのお役立ちTips

ContainerView 親ビューから子ビューを操作したい

iOSのアプリ開発でコンテナビュー(ContainerView)が便利なので使ってみました。
その際、子ビューから別の子ビューのメソッドを実行して操作したい、ということがありました。

やってみるとそこまで難しくなかったので、簡単にご紹介したいと思います。

パターンとして、親ビューから子ビュー、子ビューから親ビュー、子ビューから別の子ビューの3通りをご紹介します。

親ビューから子ビュー

子ビュー側

class ChildController: UIViewController {
    func test() {
        //code
    }
}

親ビュー側

let targetVC = childViewControllers[0] as! ChildController
targetVC.test()

子ビューから親ビュー

親ビュー側

class ParentController: UIViewController {
    func test() {
        //code
    }
}

子ビュー側

let parentVC = self.parent as! ParentController
parentVC.test()

続きを読む…»

10,912 views

スクリーンショットを添付してメール送信

MFMailComposeViewControllerを使ってメールを作成します。

まずはMessageUIをインポートします。

import MessageUI

デリゲートを追加します。

class sample: UIViewController, MFMailComposeViewControllerDelegate {
func mail(subject: String, mailbody: String) {
    let composeVC = MFMailComposeViewController()
    composeVC.mailComposeDelegate = self

    composeVC.setToRecipients(["送信先メールアドレス"])

    composeVC.setSubject(subject)

    composeVC.setMessageBody(mailbody, isHTML: false)

    let layer = UIApplication.shared.keyWindow?.layer
    let scale = UIScreen.main.scale
    UIGraphicsBeginImageContextWithOptions((layer?.frame.size)!, false, scale)

    layer?.render(in: UIGraphicsGetCurrentContext()!)
    let screenshot = UIGraphicsGetImageFromCurrentImageContext()
    let image = UIImageJPEGRepresentation(screenshot!, 1.0)
    UIGraphicsEndImageContext()

    composeVC.addAttachmentData(image!, mimeType: "image/png", fileName: "screenshot.png")

    self.present(composeVC, animated: true, completion: nil)
}

デリゲートで必要なメソッド
メール送信やキャンセルの操作を受けて実行されます。

func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
    controller.dismiss(animated: true, completion: nil)

    switch result {
    case .sent: //送信
            break
    case .saved: //保存
            break
    case .failed: //失敗
            break
    case .cancelled: //キャンセル
            break
    default:
        break
    }
}

Xcode: 8.3.2
Swift: 3.1
OS: Sierra 10.12

1,589 views

GoogleMapの操作 for iOS

GoogleMapの位置や、ズームレベルを変更します。

指定した座標に位置を設定
座標はCLLocationCoordinate2Dで渡します。

let update = GMSCameraUpdate.setTarget(coordinate)

GoogleMapを更新する

mapView.moveCamera(update)

アニメーションで更新する

mapView.animate(with: update)
その他の操作
ZoomIn ズームレベルを1.0拡大
ZoomOut ズームレベルを1.0縮小
ZoomTo ズームレベルを指定します。

それ以外の操作は公式リファレンスを参照ください。
https://developers.google.com/maps/documentation/ios-sdk/views?hl=ja

Xcode: 8.3.2
Swift: 3.1
OS: Sierra 10.12

1,476 views

座標から住所に変換する 逆ジオコーディング

緯度経度の座標から逆ジオコーディング(リバースジオコーディング)で住所を取得することができます。
これにはGoogleのAPIを利用しますので、GoogleMapsをインポートしている前提でのお話です。

座標をGoogleMapから取得します。
例えばタップであればcoordinate: CLLocationCoordinate2Dが取得できますので
これを元にCLLocationオブジェクトを作成します。

let location: CLLocation = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)

逆ジオコーディングを行うメソッド
結果をアラートで表示しています。

func ReverseGeocoder(location: CLLocation) {

    var address: String = ""

    CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error)->Void in

        if error != nil {
            print("error")
            return
        }

        if placemarks!.count > 0 {
            let pms = placemarks![0]
            address = self.makeAddressString(placemark: pms)

            let aTitle = "住所表示"
            let aMessage = address
            let alert = UIAlertController(title: aTitle, message: aMessage, preferredStyle: .alert)

            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))

            self.present(alert, animated: false, completion: nil)

        } else {

            print("error")

        }

    })

}

取得できた住所を一連の文字列に変換するメソッド

func makeAddressString(placemark: CLPlacemark) -> String {

    var address: String = ""

    //address += placemark.postalCode != nil ? placemark.postalCode! : ""
    address += placemark.administrativeArea != nil ? placemark.administrativeArea! : ""
    address += placemark.subAdministrativeArea != nil ? placemark.subAdministrativeArea! : ""
    address += placemark.locality != nil ? placemark.locality! : ""
    address += placemark.subLocality != nil ? placemark.subLocality! : ""
    address += placemark.thoroughfare != nil ? placemark.thoroughfare! : ""
    address += placemark.subThoroughfare != nil ? placemark.subThoroughfare! : ""

    return address

}

Xcode: 8.3.2
Swift: 3.1
OS: Sierra 10.12

3,762 views

アラートを表示する UIAlertController

アラートを表示するにはUIAlertControllerを利用します。

アラート(ダイアログ)を表示する

タイトルとメッセージを設定し、アラートのオブジェクトを作成します。

let aTitle = "タイトル"
let aMessage = "メッセージ表示"

let alert = UIAlertController(title: aTitle, message: aMessage, preferredStyle: .alert)

OKボタンを作成します。

alert.addAction(
    UIAlertAction(title: "OK", style: .default, handler: { action in
        print("OKをタップした場合の処理")
    })
)

キャンセルボタンを作成します。
処理は何もしないので、handlerはnilで大丈夫です。

alert.addAction(UIAlertAction(title: "キャンセル", style: .cancel, handler: nil))

アラートを表示する

self.present(alert, animated: false, completion: nil)

続きを読む…»

3,383 views