@IBOutlet weak var textField: UITextField!
@IBOutlet weak var webView: UIWebView!
@IBOutlet weak var backButton: UIBarButtonItem!
@IBOutlet weak var forwardButton: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
// string -> NSURL -> NSURLRequest -> webView.loadRequest
let startUrl = "http://hogehoge.com"
if let url = NSURL(string: startUrl){
let urlRequest = NSURLRequest(URL: url)
self.webView.loadRequest(urlRequest)
}
}
Category: Swift / SwiftUI
姓名診断 app

tips
ctl + button -> segue: show
seque identifier -> class name
command + = -> size調整
file -> new file -> Cocoa Class : 新しいclassを生成 -> utility custom classでclass設定
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.textField.text = ""
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func showAlert() {
let VERSION: Float = (UIDevice.currentDevice().systemVersion as NSString).floatValue
if VERSION >= 8.0 {
let alertController = UIAlertController(title: "Error", message: "Please enter your name", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(defaultAction)
self.presentViewController(alertController, animated: true, completion: nil)
} else {
let alert = UIAlertView()
alert.title = "Error"
alert.message = "Please enter your name"
alert.addButtonWithTitle("OK")
alert.show()
}
}
override func shouldPerformSegueWithIdentifier(identifier: String?, sender: AnyObject?) -> Bool {
if identifier == "showResult" {
if self.textField.text == "" {
self.showAlert()
return false
}
return true
}
return true
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showreResult" {
let resultViewController: ResultViewController = segue.destinationViewController as! ResultViewController
resultViewController.myName = self.textField.text
self.textField.resignFirstResponder()
}
}
}
import UIKit
class ResultViewController: UIViewController {
var myName: String = ""
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var scoreLabel: UILabel!
override func viewDidLoad(){
super.viewDidLoad()
self.nameLabel.text = "\(self.myName)の点数は..."
let score = arc4random_uniform(101)
self.scoreLabel.text = "\(score)点"
}
}
omikuji app
swiftではarcNrandom_uniform(UInt32(hoge.count))でランダムに数値を生成します。
Tips
command + option + 0: utility 非表示
launch screen -> main.storyboardに変更可能

import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myLabel: UILabel!
@IBAction func getOmikuji(sender: AnyObject) {
let results = [
"大吉",
"吉",
"中吉",
"凶",
"大凶"
]
// arc4random_uniform(n + 1)
let random = arc4random_uniform(UInt32(results.count))
if random == 0 {
self.myLabel.textColor = UIColor.redColor()
} else {
self.myLabel.textColor = UIColor.blackColor()
}
self.myLabel.text = results[Int(random)]
}
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.
}
}
Swift coding

//var s: String?
//s = nil
let name: String? = "yamada"
let msg = "hello " + name!
if name != nil {
let msg = "hello " + name!
}
if let s = name {
let msg = "hello " + s
}
var label: String!
label = "score"
println(label)
function
//func sayHi(){
// println("hi")
//}
//sayHi()
func sayHi(name: String){
println("hi " + name)
}
sayHi("satoshi")
func sayHi(myname name: String){
println("hi " + name)
}
sayHi(myname: "satoshi")
func sayHi(#name: String = "jiro"){
println("hi " + name)
}
sayHi(name: "satoshi")
列挙型
enum Result {
case Success
case Error
func getMessage() -> String {
switch self {
case .Success:
return "OK"
case .Error:
return "OK"
}
}
}
var r: Result
r = Result.Success
r = .Success
Result.Error.rawValue
class
class User {
var name: String
var score: Int = 0
init(name: String){
self.name = name
}
func updrade() {
score++
}
}
var tom = User(name: "Tom")
tom.name
tom.score
tom.updrade()
tom.score
継承
class User {
var name: String
var score: Int = 0
init(name: String){
self.name = name
}
final func upgrade() {
score++
}
}
class AdminUser: User {
func reset(){
score = 0
}
override func upgrade(){
score += 3
}
}
protocol
protocol Student {
var studentId: String { get set }
func study()
}
class User: Student {
var name: String
var score: Int = 0
var studentId: String = "hoge"
func study(){
println("studying.....")
}
init(name: String){
self.name = name
}
func upgrade() {
score++
}
}
var tom = User(name: "Tom")
tom.name
tom.score
tom.upgrade()
tom.score
willSet, didSet
class User {
var name: String
var score: Int = 0 {
willSet{
println("\(score) -> \(newValue)")
}
didSet {
println("\(oldValue) -> \(score)")
}
}
var level: Int {
get{
return Int(score / 10)
}
set {
score = Int(newValue * 10)
}
}
init(name: String){
self.name = name
}
func upgrade() {
score++
}
}
optional chaining
class User {
var blog: Blog?
}
class Blog {
var title = "My Blog"
}
var tom = User()
tom.blog = Blog()
tom.blog?.title
if let t = tom.blog?.title {
println(t)
}
type casting
class User {
var name: String
init(name: String){
self.name = name
}
}
class AdminUser: User {}
let tom = User(name: "Tom")
let bob = AdminUser(name: "Bob")
let steve = someUser()
let users: [AnyObject] = [tom, bob, steve]
for user in users {
if let u = user as? AdminUser {
println(u.name)
構造体
struct UserStruct {
var name: String
var score: Int = 0
init(name: String){
self.name = name
}
mutating func upgrade(){
score++
}
}
拡張
extension String {
var size: Int {
return countElements(self)
}
func dummy() -> String {
return "dummy"
}
}
var s: String = "hoge"
s.size
s.dummy()
generics
func getArray(item: T, count: Int) -> [T] { var result = [T]() for _ in 0..
getting started Swift
X-codeのplaygroundでコードと実行結果を表示します。
//print("hello world")
print("hello world")
変数
//var msg: String
//msg = "hello world"
//変更ができない変数 let
//var msg = "hello world"
var msg = "hello"
let s = "hoge"
//s = "bar"
println("msg: \(msg), s: \(s)")
データ型
// String, Int, Float/Double, Bool, nil // + - * / % let x: Float = 8.0 % 2.5 var y = 0 y++ y let s = "hello " + "world" true && true true || false !true let a = "hkt" let b = 48 let c = a + String(b)
タプル: _xxx はxxxを破棄
//let error = (40, "not found") //error.0 //error.1 let error = (code:40, msg:"not found") error.code error.msg let error = (40, "not found") //let (code, msg) = error let (code, _msg) = error code msg
swift
var colors: [String] = ["blue", "pink"]
colors[0]
colors[1] = "red"
colors
colors.count
colors.isEmpty
colors.append("green")
colors.insert("gray", atIndex: 1)
let secondColor = colors.removeAtIndex(1)
dictionary
var users: [String: Int] = [
"yamada": 500,
"tanaka" : 800
]
users["yamada"]
users.count
users.isEmpty
users["ito"] = 900
users
users.removeValueForKey("ito")
users
users.updateValue(1000, forKey: "tanaka")
let keys = Array(users.keys)
let values = Array(users.values)
var emptyDictionary = [String: Int]()
if
let score = 72
var result = ""
if score > 80 {
result = "Great"
} else if score > 60 {
result = "good"
} else {
result = "soso..."
}
result = score > 80 ? "great" : "so so..."
switch
let num = 7
switch num {
case 0:
println("zero")
case 1, 2, 3:
println("small")
case 4...6:
println("4/5/6")
case 7..<9:
println("7/8")
case let n where n > 10:
println("huge")
default:
println("n.a.")
}
while
var n = 0
//while n < 10 {
// println(n)
// n++
//}
do {
println(n)
n++
} while n < 10
[/code]
for
for var i = 0; i < 10; i++ {
println(i)
}
for i in 0...9 {
println(i)
}
let a = [5, 3, 10]
for i in a {
println(i)
}
View Controller Scene

developer向けサイト:https://developer.apple.com
developerプログラム:https://developer.apple.com/programs/jp/
ctrl で、support editorにひも付けて、変数myLableにchnageLabelしています。
@IBOutlet weak var myLabel: UILabel!
@IBAction func changeLabel(sender: AnyObject) {
myLabel.text = "You changed me"
}
tips
command + 0 ->navigator area削除
auto size, auto layout on
story board -> assistant editor -> preview
upgrade frames ->制約に自動調整, items new constrainsで作成時につけることも可能
clear constrains ->制約を解除
上下左右幅いっぱいにするには margin 0

constrain: Editor -> pin -> height or width
view ctrl + dragでも可能
viewを2つ選択して equal height
multiplier: 2つのviewの比率を設定

labelなどのtextはxcode側でサイズを自動計算するので、必ずしも指定しなくてOK
content Hugging priority 大きくなりにくさ
deviceごとに表示を変えるには、画面下のsize classで設定