Last active
December 6, 2017 07:35
-
-
Save Curookie/4d22faaa866af3d9acc10de5f969488c to your computer and use it in GitHub Desktop.
iOS Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
한 프로젝트에 template을 여러개 붙일 수 없다. | |
info.plist : 환경변수 파일 | |
*.swift : 클래스 파일 | |
AppDelegate.swift : 실행주기 관리하는 내용 | |
ViewController.swift : 화면의 뷰를 관리하는 내용 - 코딩 수정 | |
Main.storyboard : UI 화면설계 - 화면 수정 | |
기본 편집기 : UI 수정 | |
보조 편집기 : 코드 수정 | |
오른쪽 상단에 =, ㅇㅇ, < > 버튼 3가지 있는데 기본, 보조(2개보기), ?? 보기다. | |
*아웃렛 변수, *액션 함수 | |
실수하면 이벤트 헨들러에서 제거 해야한다. | |
weak, strong은 중요하지 않다. | |
;는 입력하지 않아도 되고 !를 입력한다. | |
@클래스명 | |
!는 값을 가져올 때 | |
? 옵셔널 변수 어떤값이 올지 알 수 없는 것들 기본값 null | |
: -> 상속의 의미, 여러개 상속 가능 | |
"_ " 복수 개 일경우는 _ 한칸띄워줘야한다. | |
control을 누르고 보조 편집기에 끌면 빠른 선언 가능 | |
자동완성기능을 써야 오류를 막을 수 있다. | |
// ImageView | |
기기별 해상도 차이 생각해야한다. 하위 상위 2배이상 차이남 | |
let scale:?? = 2.0 상수로 씀 | |
var newWidth:CGFloat, newHeight:CGFloat | |
viewDidLoad 함수란 만든 뷰를 불러왔을 때 호출되는 함수이다. | |
배열은 var a = [ 1, 2, 3, 4 ] 이렇게 선언 | |
비율은 아래 4번째 아이콘으로 | |
날짜를 나타나게 해주는 데이트 피커 | |
현재시간을 가져오는 NSDate() | |
let ??? = DateFormatter() 클래스 상수 선언 | |
as는 캐스트 연산자 | |
#은 함수를 붙여줄 때 사용하는 연산자 | |
dateFormat | |
EEE - 요일 나타냄 3글자로 | |
aaa - AM PM | |
PickerView로 사진이나 글자 스크롤 하는 뷰 만들 수 있다. | |
옵션중에 여러개 굴리게 할 수 있는 옵션이 있다. | |
delegate numberOfComponentsInPickerView, PickerView Count | |
View Controller 아이콘에 오른쪽버튼으로 어떤 아울렛 오브젝트를 끌어놓으면 delegate로 선언할 수 있는 옵션을 볼 수 있다. | |
델리게이트(대리자) | |
메인 프로세스는 프로세스를 계속 하게하고 대신 넘겨준 것을 처리하는 역할 | |
swift에서는 delegate가 이벤트 핸들러같은 역할을 하는 것 같다. | |
반복문 형식 | |
for in Range, for in 0...9, for in 0..<10 | |
배경 색 바꾸는건 self.view.backgroundColor = UIColor.red | |
command + 마우스클릭 => 소스 연결 보기 | |
alert : 경고창 | |
lampOffAlert.addAction(offAction) | |
lampOffAlert.addAction(cancelAction) | |
present(lampOffAlert, animated: true, completion: nil) | |
self 자기자신 객체를 지정한다. | |
익명 함수는 함수명을 쓰지않고 func도 안쓴다. 일회용 함수다. 편하게 쓰기위해 생긴 것 | |
in 을 사용한다. | |
destructive 빨간색 | |
command + shift + 4 : 화면캡쳐 | |
중간고사 17 | |
앞장 구멍 12개 번호 써넣는거 60점 | |
뒷장 5문제 2장빼고 3,4,5,6장에서 나옴 | |
14개 5점짜리 70점 | |
3개 10점짜리 문제 30점 | |
10점 7개중 3개 | |
스위프트의 실제 장점 기술, 델리게이트에 대한 설명 , | |
엑스코드와스토리보드, 기본자료형중 케릭터와 스트링에대한 설명, | |
익명함수가 뭔지, for loop가 무엇인지 어떻게 쓰는건지?, Alert에 대해서 설명하는 것 | |
5점 6개 2개 | |
스위프트에서 옵셔널로 값이없는 변수와함께 사용하는 기호는 | |
문자열을 합칠때 사용하는 연산자 | |
클래스를 상속받기 위해 클래스오른쪽에 사용하는 기호는? | |
아이폰에서 원하는 항목을 선택하게해주는 객체는 무엇인가? | |
앱에서 사진들을 보여줘야할때 사용되는 객체는? | |
앱에서 날짜나 시간을 보여줘야할때 사용되는 객체는? | |
page control | |
슬라이드로 많이 쓰는 기능. 도커라고도 하는 페이지를 이동할 때 사용하는 객체이다. | |
메서드로는 | |
numberOfPages int (count) | |
currentPage= int (0) | |
pageIndicatorTintColor = UIColor.?? | |
currentPageIndicatorTintColor = UIColor.?? | |
의 메서드가 있다. | |
기말고사 내면 10점 실제 30점 총 40점 배점, 7 8 10 11 12 시험시간에 실습 시험, 도전미션에 크게 벗어나지 않을 것이다. | |
웹 뷰(Web View) : 웹을 보여주는 틀 | |
툴 바(Tool Bar) : 여러개의 도구(버튼)들의 집합 | |
툴바 안에서 버튼은 빈공간을 차지하는 플렉시블 버튼과 실제 버튼인 바 버튼이 있다. | |
Flexible Space Bar Button Item과 Bar Button Item | |
Show the Attributes inspector > System Item > Custom 을 다른 아이콘으로 바꿀 수 있다. | |
Activity Indicator View 는 로딩을 표현하는 도구다. | |
- Behavior의 Hides When Stopped 버튼을 활성화 시켜줘야한다. | |
코드 옆에 왼쪽 회색 동그라미가 연결된 것을 표시한다. | |
**** info.plist 환경설정 파일 >> App Transport Security 수정 | |
-> 웹 보안 설정해야 웹 뷰에서 웹 뜬다. | |
Allow Arbitrary Loads >> Yes 로 설정 | |
클래스도 추가해야함 UIWebViewDelegate 액티비티 인디케이터 조정하기 위해서 | |
Bundle.main Bundle 에서 main으로 변수를 생성할 때 사용한다. | |
함수의 리턴타입은 func 함수명(매개변수) -> 리턴타입 { } 이런식으로 설계한다. | |
세그먼트 컨트롤은 탭 기능을하는 객체이다. | |
MKMapView 맵뷰 객체 | |
import UIkit 밑에 import MapKit 해야한다. | |
MapKit안에 있는 CLLocationManagerDelegate 클래스를 상속한다. | |
let locationManager = CLLocationManager() | |
locationManager.delegate = self // 델리게이트를 self로 설정 | |
locationManager.desiredAccuracy = kCLLocationAccuracyBest // 정확도를 최고로 설정 | |
locationManager.requestWhenInUseAuthorization() // 위치 데이터를 추적하기 위해 사용자에게 자동으로 승인을 요구 | |
locationManager.startUpdatingLocation() // 위치 업데이트 시작 | |
myMap.showsUserLocation = true // 위치보기 값을 트루로 설정 | |
Info.plist 수정해야 한다. | |
Information Property List >> Privacy - Location When In Use Usage Description >> App needs location servers for stuff. | |
command + shift + H 눌러서 홈으로 이동해서 settings 렝기지&로케이션 한국어 대한민국으로 바꿈 | |
위치,경도 표현하기 위해서는 goLocation함수를 만든다. | |
(책에서는 _= 이 빠져있는데 이거 써야 에러 안난다.) | |
업데이트 되었을 경우 처리할 locationManager함수도 만들어야한다. | |
ex) | |
func goLocation(latitude latitudeValue: CLLocationDegrees, longitude longitudeValue: CLLocationDegrees, delta span :Double) { | |
let pLocation = CLLocationCoordinate2DMake(latitudeValue, longitudeValue) | |
// 위도, 경도 값을 매개변수로 하여 CLLocationCo | |
let spanValue = MKCoordinateSpanMake(span, span) | |
let pRegion = MKCoordinateRegionMake(pLocation, spanValue) | |
myMap.setRegion(pRegion, animated: true) | |
} | |
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { | |
let pLocation = locations.last | |
_=goLocation(latitude: (pLocation?.coordinate.latitude)!, longitude: (pLocation?.coordinate.longitude)!, delta: 0.01) | |
CLGeocoder().reverseGeocodeLocation(pLocation!, completionHandler: { | |
(placemarks, error) -> Void in | |
let pm = placemarks!.first | |
let country = pm!.country | |
var address:String = country! | |
if pm!.locality != nil { | |
address += "" | |
address += pm!.locality! | |
} | |
if pm!.thoroughfare != nil { | |
address += "" | |
address += pm!.thoroughfare! | |
} | |
self.lblLocationInfo1.text = "현재 위치" | |
self.lblLocationInfo2.text = address | |
}) | |
locationManager.stopUpdatingLocation() | |
} | |
현재 위치 정보 보여주기 | |
Debug > Location > Custom Location... 선택하면 된다. // 그외 애플사도 보여줄 수 있다. | |
37.56647 | |
126.977963 | |
서울 시청 위도 경도 예 | |
핀 추가 코드 | |
goLocation 함수도 변경해야한다. | |
func goLocation(latitude latitudeValue: CLLocationDegrees, longitude longitudeValue: CLLocationDegrees, delta span :Double) -> CLLocationCoordinate2D { | |
let pLocation = CLLocationCoordinate2DMake(latitudeValue, longitudeValue) | |
let spanValue = MKCoordinateSpanMake(span, span) | |
let pRegion = MKCoordinateRegionMake(pLocation, spanValue) | |
myMap.setRegion(pRegion, animated: true) | |
return pLocation | |
} | |
func setAnnotation(latitude latitudeValue: CLLocationDegrees, longitude longitudeValue : CLLocationDegrees, delta span :Double, title strTitle: String, subtitle strSubtitle:String) { | |
let annotation = MKPointAnnotation() | |
annotation.coordinate = goLocation(latitude: latitudeValue, longitude: longitudeValue, delta: span) | |
annotation.title = strTitle | |
annotation.subtitle = strSubtitle | |
myMap.addAnnotation(annotation) | |
} | |
세그먼트 눌렀을 때 코드 | |
@IBAction func sgChangeLocation(_ sender: UISegmentedControl) { | |
if sender.selectedSegmentIndex == 0 { | |
self.lblLocationInfo1.text="" | |
self.lblLocationInfo2.text="" | |
locationManager.startUpdatingLocation() | |
} else if sender.selectedSegmentIndex == 1 { | |
setAnnotation(latitude: 37.4480065, longitude: 126.6553179, delta: 1, title: "인하공업전문대학", subtitle: "인천광역시 남구 인하로 100") | |
self.lblLocationInfo1.text = "보고 계신 위치" | |
self.lblLocationInfo2.text = "인하공업전문대학" | |
} else if sender.selectedSegmentIndex == 2 { | |
setAnnotation(latitude: 37.5307871, longitude: 126.8981, delta: 0.1, title: "이지스퍼블리싱", subtitle: "서울특별시 영등포구 당산로 41길 11") | |
self.lblLocationInfo1.text = "보고 계신 위치" | |
self.lblLocationInfo2.text = "이지스퍼블리싱 출판사" | |
} else if sender.selectedSegmentIndex == 3 { | |
setAnnotation(latitude: 37.4484319, longitude: 126.6615897, delta: 0.05, title: "종진이네 집", subtitle: "인천광역시 남구 용현1,4동 84-36") | |
self.lblLocationInfo1.text = "보고 계신 위치" | |
self.lblLocationInfo2.text = "동그라미 종지니네 집" | |
} | |
} | |
탭을 만드는 것은 | |
아이폰 화면을 클릭한 후 Editor → Embed In → Tab Bar Controller 탭 영역만들수있음 | |
소스는 | |
.swift 파일 복제해서 끌어온다 | |
그리고 class명을 다른 걸로 수정한다. | |
틀은 | |
Base.Iproj Main.storyboard 열어서 드래그 복사할 곳에 복사한다음 오른쪽 버튼으로 끌어서 놓고 | |
view Controllers 하고 class명을 ImageViewController | |
imageView는 파일옵션으로 image파일명을 코딩하지 않고 선택해서 디폴트로 정할수도 있다. | |
네비게이션 컨트롤러 | |
- 서로 연관성 있는 데이터를 가지고 있는 화면 전환시에 사용하는 기능으로 주고받을 수 있다. | |
- Editor -> Embed in -> Navigation Controller 선택하기 | |
- 네비게이션 바 더블클릭 시 이름 지정가능 | |
- barbuttonitem을 넣으면 네비게이션바에 버튼넣을수 있음 | |
- viewcontroller를 스토리보드에 넣으면 새로운 뷰를 만들어낼수있다. | |
- barbuttonitem -> edit으로 바꾸고 -> 버튼 종류를 오른쪽버튼으로 끌어 새로운 뷰에 끌어 show를 선택하면 이동할 수 있는 링크(segue) 세그웨이가 생성된다. | |
- viewController 의 이름을 Title로 바꿀 수 있다. | |
- segue의 이름을 정할 수 있다. identifier로 | |
- 스위프트 소스 파일 추가 대부분 cocoa touch class로 추가한다. 유니티의 라이브러리같은 개념 | |
- viewcontroller를 .swift 파일을 identify inspector 버튼 -> Custom Class 옵션에서 클래스 지정해줄 수 있다. | |
- prepare함수로 segue간의 데이터 통신 가능 | |
- Autometic/Manual 옵션에서 .swift 파일을 고를 수 있다. | |
- 프로토콜은 특정 객체가 갖추어야 할 기능이나 속성에 대한 설계도. 실질적으로 아무런 내용이 없다. 다만 단순한 선언 형태만 갖는다. | |
Storyboard ID를 사용해서 화면전환을 할 수 있다. 약간의 코드와 함께~ | |
테이블 뷰 | |
- 뷰 컨트롤러 | |
Is Initial View Controller 체크 - 처음 시작할때 보여주는 것 지정 | |
Selection Sague | |
뷰 두개 생성 | |
Detail View에만 sgDetail 아이덴티파이 명 정해줌 데이터 교환하기위해 | |
Main View의 Prototype Cells 클릭 후 아이덴티파이 - myCell | |
Add View / Detail View | |
Table, Add, Detail | |
UITableViewController - Table, | |
UIViewController - Add, | |
UIViewController - Detail | |
.swift | |
화면 연결, class 연결 | |
tableView를 변수화 한다. | |
나머지 텍스트 필드랑 버튼, 라벨 변수화 한다. | |
테이블 목록 보여주기 | |
전역변수 처리 | |
var = [ 배열처리] 이미지 불러와 변수화함 | |
numberOfSections return 0 -> 1 섹션값 | |
tableView 0 -> items.count 열의 개수 = 이미지의 개수 | |
앞에서 선언한 함수 적용하는 함수 주석해제 | |
myCell, 적용하고 함수만들기 | |
삭제하는 함수 주석 해제, 한글버튼 주석 해제 | |
수정 버튼 만들기 -> //, () 삭제 | |
움직이는 메뉴 주석 해제 | |
코드 넣고 | |
추가 스위프트 가서 추가하는 버튼에 추가넣고 | |
목록 리뉴얼 | |
Detail 뷰 텍스트 받게 코딩 | |
table 뷰에서 prepare 함수 세그웨이를 이용해서 뷰를 이동하는 함수 주석 해제 | |
detail에 넘겨주는 코드 추가 | |
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { | |
// Get the new view controller using segue.destinationViewController. | |
// Pass the selected object to the new view controller. | |
if segue.identifier == "sgDetail" { | |
let cell = sender as! UITableViewCell | |
let indexPath = self.tvListView.indexPath(for: cell) | |
let detailView = segue.destination as! DetailViewController | |
detailView.receiveItem(items[((indexPath as NSIndexPath?)?.row)!]) | |
} | |
} | |
// | |
// ViewController.swift | |
// Navigation | |
// | |
// Created by 407-41 on 2017. 11. 29.. | |
// Copyright © 2017년 Curookie. All rights reserved. | |
// | |
import UIKit | |
class ViewController: UIViewController, EditDelegate { | |
let imgOn = UIImage(named: "lamp_on.png") | |
let imgOff = UIImage(named: "lamp_off.png") | |
var isOn = true | |
var isZoom = false | |
var onZoomFlag = false | |
@IBOutlet weak var txMessage: UITextField! | |
@IBOutlet weak var imgView: UIImageView! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Do any additional setup after loading the view, typically from a nib. | |
imgView.image = imgOn | |
} | |
override func didReceiveMemoryWarning() { | |
super.didReceiveMemoryWarning() | |
// Dispose of any resources that can be recreated. | |
} | |
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { | |
let editViewController = segue.destination as! EditViewController | |
if segue.identifier == "editButton" { | |
editViewController.textWayValue = "segue : use button" | |
} else if segue.identifier == "editBarButton" { | |
editViewController.textWayValue = "segue : use Bar button" | |
} | |
editViewController.textMessage = txMessage.text! | |
editViewController.delegate = self | |
editViewController.isOn = isOn | |
editViewController.isZoom = isZoom | |
editViewController.onZoomFlag = onZoomFlag | |
} | |
func didMessageEditDone(_ controller: EditViewController, message: String) { | |
txMessage.text = message | |
} | |
func didImageOnOffDone(_ controller: EditViewController, isOn: Bool) { | |
if isOn { | |
imgView.image = imgOn | |
self.isOn = true | |
} else { | |
imgView.image = imgOff | |
self.isOn = false | |
} | |
} | |
func didImageZoomDone(_ controller: EditViewController, isZoom: Bool, onZoom: Bool) { | |
let scale:CGFloat = 2.0 | |
var newWidth:CGFloat, newHeight:CGFloat | |
if isZoom && !onZoom { | |
newWidth = imgView.frame.width*scale | |
newHeight = imgView.frame.height*scale | |
imgView.frame.size = CGSize(width: newWidth, height: newHeight) | |
self.isZoom = true | |
onZoomFlag = true | |
} else if !isZoom && onZoom { | |
newWidth = imgView.frame.width/scale | |
newHeight = imgView.frame.height/scale | |
imgView.frame.size = CGSize(width: newWidth, height: newHeight) | |
self.isZoom = false | |
onZoomFlag = false | |
} | |
} | |
} | |
// | |
// EditViewController.swift | |
// Navigation | |
// | |
// Created by 407-41 on 2017. 11. 29.. | |
// Copyright © 2017년 Curookie. All rights reserved. | |
// | |
import UIKit | |
protocol EditDelegate { | |
func didMessageEditDone(_ controller: EditViewController, message: String) | |
func didImageOnOffDone(_ controller: EditViewController, isOn: Bool) | |
func didImageZoomDone(_ controller: EditViewController, isZoom: Bool, onZoom: Bool) | |
} | |
class EditViewController: UIViewController { | |
var textWayValue: String = "" | |
var textMessage: String = "" | |
var delegate: EditDelegate? | |
var isOn = false | |
var isZoom = false | |
var onZoomFlag = false | |
@IBOutlet weak var swIsOn: UISwitch! | |
@IBOutlet weak var lblWay: UILabel! | |
@IBOutlet weak var txMessage: UITextField! | |
@IBOutlet weak var btnResize: UIButton! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Do any additional setup after loading the view. | |
lblWay.text = textWayValue | |
txMessage.text = textMessage | |
swIsOn.isOn = isOn | |
if(isZoom) { | |
btnResize.setTitle("확대", for: .normal) | |
} else { | |
btnResize.setTitle("축소", for: .normal) | |
} | |
} | |
override func didReceiveMemoryWarning() { | |
super.didReceiveMemoryWarning() | |
// Dispose of any resources that can be recreated. | |
} | |
@IBAction func btnDone(_ sender: UIButton) { | |
if delegate != nil { | |
delegate?.didMessageEditDone(self, message: txMessage.text!) | |
delegate?.didImageOnOffDone(self, isOn: isOn) | |
delegate?.didImageZoomDone(self, isZoom: isZoom, onZoom: onZoomFlag) | |
} | |
_ = navigationController?.popViewController(animated: true) | |
} | |
@IBAction func swImageOnOff(_ sender: UISwitch) { | |
if sender.isOn { | |
isOn = true | |
} else { | |
isOn = false | |
} | |
} | |
@IBAction func btnResizeImage(_ sender: UIButton) { | |
if isZoom { | |
isZoom = false | |
btnResize.setTitle("축소", for: .normal) | |
} else { | |
isZoom = true | |
btnResize.setTitle("확대", for: .normal) | |
} | |
} | |
/* | |
// MARK: - Navigation | |
// In a storyboard-based application, you will often want to do a little preparation before navigation | |
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { | |
// Get the new view controller using segue.destinationViewController. | |
// Pass the selected object to the new view controller. | |
} | |
*/ | |
} | |
시험은 인터넷 연결 안되고, 노트북 안되고, 오픈북, usb받아오는건 허용 | |
수요일 2시에 시험 시작. | |
20일날 보강 주 나와야한다. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment