티스토리 뷰
728x90
Optional
출처 : 옵셔널 (Optional)
//: Playground - noun: a place where people can play import UIKit var email: String? print(email) // nil nickname = "bluexmas" print(nickname) // Optional("bluexmas") var str = "Hello, playground" var name:Optional<string> = "name" var name2:String? = "name2" var name4:ImplicitlyUnwrappedOptional<string> = "name4"; var name3:String! = "name3" print() name2 값이 nil 아니면 name2값 출력, name2의 값이 nil 및 경우 ?? 뒤에 있는 값 출력 if name != nil { print(name!) } if val n = name { print(n) } if let n = name { print(n) } var text1:String = "abc" Int(test1) // nil var test:String = "123" print(Int(test)! + 10)
nil 전달 함수
var lampOn:Bool? = false func lampOnOffRemove(isOn : Bool?) { if let onOff = isOn { self.lampOn = onOff self.lampImageView.image = UIImage(named : onOff ? "lamp-on.png" : "lamp-off.png") } else { self.lampOn = nil self.lampImageView.image = UIImage(named : "lamp-remove.png") } } @IBAction func lampOffClicked(_ sender: AnyObject) { if lampOn! { // <-- 컴파일시 느낌표(!) 있어야 컴파일이 되고, 값이 nil 인 경우 런타임시 오류 발생 // } else { // } }
WebView HTML 문자열 로딩
@IBAction func HTMLClicked(_ sender: AnyObject) { let htmlString = "HTML String
String 변수를 이용한 웹페이지
" webView.loadHTMLString(htmlString, baseURL: nil) }
WebView HTML 파일 로딩
func loadPageWithUrlString(urlString : String) { if let url = URL(string : urlString) { webView.loadRequest(URLRequest(url: url)) } } @IBAction func fileClicked(_ sender: AnyObject) { if let path = Bundle.main.path(forResource: "Sample", ofType : "html") { loadPageWithUrlString(urlString: path) } }
WebView Delegate
class ViewController: UIViewController, UIWebViewDelegate { @IBOutlet weak var webView: UIWebView! @IBOutlet weak var loadingIndicator: UIActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.webView.delegate = self } public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { guard let urlString = request.url?.absoluteString else { return true; } print(request.url?.absoluteString ?? "") if urlString.contains("daum.net") { return false; } return true; } public func webViewDidStartLoad(_ webView: UIWebView) { loadingIndicator.startAnimating() } public func webViewDidFinishLoad(_ webView: UIWebView) { loadingIndicator.stopAnimating() } public func webView(_ webView: UIWebView, didFailLoadWithError error: Error) { print(error.localizedDescription) loadingIndicator.stopAnimating() }
포커스 이동
// 텍스트필드 컨트롤에 포커서를 줘서 키패드가 자동으로 올라오도록 함 self.urlTextField.becomeFirstResponder()
Objective-C main 함수
출처 : The App Life Cycle
// // main.m // study2 // // Created by Mac on 2017. 5. 27.. // Copyright © 2017년 Mac. All rights reserved. // #import <uikit uikit.h=""> #import "AppDelegate.h" int main(int argc, char * argv[]) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); } }
UIImageView 확대
@IBAction func OnBtnScaleClick(_ sender: UIButton) { imgLamp.frame.size.width *= 1.2 imgLamp.frame.size.height *= 1.2 }
형변환
@IBAction func typeCast(_ sender: AnyObject) { if let tmpButton = sender as? UIButton { tmpButton.setTitle("확대2", for: .normal) } }
loadImage 함수 구현
func loadImage(fileName : String, fileType : String) -> UIImage? { if let path = Bundle.main.path(forResource: fileName, ofType: fileType) { return UIImage(contentsOfFile : path) } else { return nil; } } @IBAction func OnRadio1Change(_ sender: UISwitch) { imgLamp.image = loadImage( fileName : sender.isOn ? "lamp_on.png" : "lamp_off.png", fileType : "png" ) }
TextField Delegate
public func textFieldShouldReturn(_ textField: UITextField) -> Bool // called when 'return' key pressed. return NO to ignore. { loadPageWithUrlString(urlString: urlTextField.text ?? "") // 포커스 해지 view.endEditing(true) return true; }
배열추가, String format, 이미지 변경
var flowerArray = [String]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. for i in 1...6 { flowerArray.append( String(format : "%02d.png", i)) } } @IBAction func onBtnNextClick(_ sender: UIButton) { if sender.currentTitle == "이전" { current_img_index -= 1 } else { current_img_index += 1 } if current_img_index >= flowerArray.count { current_img_index = 0 } if current_img_index < 0 { current_img_index = flowerArray.count - 1 } imgLamp.image = UIImage(named : flowerArray[current_img_index]) }
Timer
// 1초에 한번씩 호출 Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (timer) -> Void in // NSLog("%G", #function) let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy M d HH:mm:ss" self.lblCurrentTime.text = "현재시간 : " + dateFormatter.string(from : Date()) })
UIAlertController
override func viewDidAppear(_ animated: Bool) { /* let messageBox = UIAlertView(title : "알림", message : "메시지", delegate : nil, cancelButtonTitle : "OK") messageBox.show() */ let messageBox = UIAlertController(title: "알림", message: "메시지", preferredStyle: .alert) messageBox.addAction(UIAlertAction(title : "OK", style : .default, handler : { (action) -> Void in print("OK 선택") })) messageBox.addTextField(configurationHandler: { (textfield) in textfield.backgroundColor = UIColor.yellow }) present(messageBox, animated : true, completion : nil) }
picker
import UIKit class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { @IBOutlet weak var imagePickerView: UIPickerView! @IBOutlet weak var selectedItemLable: UILabel! @IBOutlet weak var selectedImageView: UIImageView! var mArray = [String]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. imagePickerView.dataSource = self imagePickerView.delegate = self for i in 1...6 { mArray.append(String(format: "%02d", i)) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // picker 열의 개수 public func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } // picker 행의 개수 public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return mArray.count; } /* func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return mArray[row] }*/ // picker 행의 높이 설정 public func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { return 100; } // picker 행을 이미지로 표시 public func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { let imageView = UIImageView(frame:CGRect(x:0, y:0, width:100, height:100)); imageView.image = UIImage(named : mArray[row]) return imageView } // 선택이벤트 public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { selectedItemLable.text = "선택 = " + mArray[row] selectedImageView.image = UIImage(named : mArray[row]) } }
이미지 비동기 로딩
if let urlString = movieArray[indexPath.row].thumbnailUrl, let url = URL(string : urlString) { do { /* // 동기방식 let imageData = try Data(contentsOf: url) cell.thumbnailImageView.image = UIImage(data : imageData) */ } catch { } // 비동기방식 let task = URLSession.shared.dataTask(with: url) { (data, response, error) -> Void in if let imageData = data { DispatchQueue.main.async { cell.thumbnailImageView.image = UIImage(data : imageData) } } } task.resume() }
동영상 플레이
func playVideo(url : URL) { let playerVC = AVPlayerViewController() let player = AVPlayer(url: url) playerVC.player = player present(playerVC, animated: true, completion: { playerVC.player?.play() }) }
댓글
300x250
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
TAG
- Linux
- Java
- android
- ffmpeg
- 전예희
- Delphi Tip
- KOBA
- Mac
- Delphi
- MySQL
- Xcode
- sas2009
- ubuntu
- 일본여행
- 레이싱모델 익스트림 포토 페스티벌
- 동경
- 서울오토살롱
- flex
- 지스타2007
- JavaScript
- oracle
- 튜닝쇼 2008
- ble
- Spring
- koba2010
- 송주경
- NDK
- BPI-M4
- Spring MVC
- SAS
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |
글 보관함