Swift - UITableView

Programming/Swift 2017.06.17 15:25 Posted by 파란크리스마스

출처 : [IOS/Swift] Custom TableView Cell 만들기 - 코딩하는 빵 - Tistory

//
//  ViewController.swift
//  TableView2
//
//  Created by bluesanta on 2017. 6. 10..
//  Copyright © 2017년 bluesanta. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    var toDoArray = ["영화보기", "야구보기", "수영하기"]

    @IBOutlet weak var toDoTableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        self.toDoTableView.dataSource = self
        self.toDoTableView.delegate = self;
    }
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return toDoArray.count
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "toDoCell", for:indexPath)
        cell.textLabel?.text = toDoArray[indexPath.row]
        return cell
    }
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        // 선택 이벤트
    }
}

Custom Cell

Custom Cell Class 생성 및 지정

Custom Cell 사용

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "tvCell", for:indexPath) as! MovieTableViewCell
        //cell.textLabel?.text = movieArray[indexPath.row].title
        cell.thumbnailImageView.image = nil
        cell.titleLabel.text = movieArray[indexPath.row].title
        cell.genreLabel.text = movieArray[indexPath.row].genre
        cell.ratingLabel.text = movieArray[indexPath.row].ratingAverage
        
        /*
        if let titleLabel =  cell.viewWithTag(11) as? UIImageView {
            titleLabel.text = movieArray[indexPath.row].title
        }
        */
    
        return cell
    }

TableView 갱신

           // 메일 쓰레드에서 화면 갱신
            DispatchQueue.main.async {
                self.tvMovie.reloadData()
            }

테이블 상단 공백 제거

- Adjust Scroll View Inserts 체크 제거

저작자 표시
신고

Swift - JSON 파싱

Programming/Swift 2017.06.17 12:43 Posted by 파란크리스마스

json 파싱

        let jsonString = "{ \"name\":\"test\", \"age\":30 }"
        if let data = jsonString.data(using: .utf8) {
            do {
                if let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject] {
                    
                    print(json["name"] ?? "")
                    print(json["age"] ?? 0)
                }
            } catch {
                print("JSON 파싱 에러")
            }
        }

원격호출 json 파싱

let urlString = "http://115.68.183.178:2029/hoppin/movies?order=releasedateasc&count=10&page=1&version=1&genreId="
        guard let url = URL(string: urlString) else { return }
        
        let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
            guard let data = data,
            let httpRes = response as? HTTPURLResponse, httpRes.statusCode == 200 else {
                return
            }

            if let error = error {
                print(error.localizedDescription)
                return;
            }
            
            do {
                if let jsonDic = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject] {
                    print(jsonDic)
                    
                    guard let totalInfo = jsonDic["hoppin"] as? [String : AnyObject],
                        let totalCount = totalInfo["totalCount"] as? String,
                        let movies = totalInfo["movies"] as? [String :AnyObject],
                        let movieArray = movies["movie"] as? [[String:AnyObject]] else {return}
                    
                    print(totalCount)
                    print(movies)
    
                    for info in movieArray {
                        print(info["title"] ?? "")
                        print(info["thumbnailImage"] ?? "")
                        
                        let movieInfo = MovieInfo(title : info["title"] as? String,
                            thumbnailUrl : info["thumbnailImage"] as? String,
                            genre : info["genreNames"] as? String,
                            ratingAverage : info["ratingAverage"] as? String)
                        self.movieArray.append(movieInfo)
                    }
                    
                    
                }
            } catch {
                print("JSON 파상 에러")
            }
            
            print("JSON 파싱 완료")
            
            // 메일 쓰레드에서 화면 갱신
            DispatchQueue.main.async {
                self.tvMovie.reloadData()
            }
        })
        
        print("JSON 파싱 시작")
        task.resume()

json 파싱 함수로 구현

    func parseJSONString(jsonString : String) -> [String:AnyObject]? {
        guard let data = jsonString.data(using: .utf8) else {
            return nil
        }
        
        do {
            if let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject] {
                print(json);
                return json
            }
        } catch {
            print("JSON 파싱 에러")
        }

        return nil
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        let jsonString = "{ \"name\":\"test\", \"age\":30 }"
        if let jsonDic = self.parseJSONString(jsonString: jsonString) {
            print(jsonDic["name"] ?? "")
            print(jsonDic["age"] ?? 0)
        }
    }
저작자 표시
신고

Swift - OpenAPI 사용하기(XMLParser 사용)

Programming/Swift 2017.06.17 11:19 Posted by 파란크리스마스

출처 : [iOS/Swift] XML 파싱하기 :: 고무망치

OPEN API 호출 및 XML 파싱

class TableViewController: UITableViewController, XMLParserDelegate {

    var xmlParser = XMLParser()
    
    var currentElement = ""                // 현재 Element
    var movieItems = [[String : String]]() // 영화 item Dictional Array
    var movieItem = [String: String]()     // 영화 item Dictionary
    
    var pubTitle = "" // 영화 제목
    var contents = "" // 영화 내용
    
    func requestMovieInfo() {
        // OPEN API 주소
        let url = "http://api.koreafilm.or.kr/openapi-data2/service/api105/getOpenDataList"
        
        guard let xmlParser = XMLParser(contentsOf: URL(string: url)!) else { return }
        
        xmlParser.delegate = self;
        xmlParser.parse()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()   
        requestMovieInfo()
    }
    
    // XMLParserDelegate 함수
    // XML 파서가 시작 테그를 만나면 호출됨
    public func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:])
    {
        currentElement = elementName
        if (elementName == "item") {
            movieItem = [String : String]()
            pubTitle = ""
            contents = ""
        }
    }
    
    // XML 파서가 종료 테그를 만나면 호출됨
    public func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?)
    {
        if (elementName == "item") {
            movieItem["title"] = pubTitle;
            movieItem["contents"] = contents;
            
            movieItems.append(movieItem)
        }
    }
    
    // 현재 테그에 담겨있는 문자열 전달
    public func parser(_ parser: XMLParser, foundCharacters string: String)
    {
        if (currentElement == "contents") {
            contents = string
        } else if (currentElement == "pubtitle") {
            pubTitle = string
        }
    }

스토리 보드에서 초기 뷰컨트롤러 지정하기

is initial view controller 체크 박스 선택

XML 결과 보여주기

withIdentifier 설정

코드

    // MARK: - Table view data source
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return self.movieItems.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "movieCell", for: indexPath)
     
        // Configure the cell...
        cell.textLabel?.text = movieItems[indexPath.row]["title"]
     
        return cell
    }

HTTP 접속 오류 해결 하기

오류 메시지 : App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.

저작자 표시
신고

Swift - 페이지 이동

Programming/Swift 2017.06.17 09:54 Posted by 파란크리스마스

출처 : 

Page View Controller

페이지 넘기기 효과

페이지 배열에 담기

    
    // lazy - 멤버가 생성되는 시점에는 메모리 할당하지 않음
    // 객체가 생성될때 초기화 함수 없이 정의만하고 객체내에서 호출시 메모리 할당
    lazy var vcArray:[UIViewController] = [self.loadVC(storyboardId: "page1VC"),
                                           self.loadVC(storyboardId: "page2VC"),
                                           self.loadVC(storyboardId: "page3VC")]
    
    // 스토리보드 ID로 ViewController 얻어오기
    func loadVC(storyboardId : String) -> UIViewController {
        return (storyboard?.instantiateViewController(withIdentifier:storyboardId))!
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        // laza 변수가 호출 되어 메모리 할당
        // static 으로 하지 않으면 객체가 만들기전에 self 함수를 호출 할 수 없지만
        // lazy 변수는 객체내에서 호출시 메모리 할당 - 미리 할당 하지 않음
        print(vcArray.count)
    }

페이지 이동 - 다음 페이지 지정

class PageViewController: UIPageViewController, UIPageViewControllerDataSource {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        guard let page1VC = vcArray.first else { return }
        self.setViewControllers([page1VC], direction: .forward, animated: true, completion: nil)
    }

    public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        
        guard let curIndex = vcArray.index(of : viewController) else {
            return nil
        }
        
        let beforeIndex = curIndex - 1
        if beforeIndex < 0 {
            return vcArray.last
        } else {
            return vcArray[beforeIndex]
        }
    }
    
    public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        
        guard let curIndex = vcArray.index(of : viewController) else {
            return nil
        }
        
        let beforeIndex = curIndex + 1
        if beforeIndex >= vcArray.count {
            return vcArray.first
        } else {
            return vcArray[beforeIndex]
        }
    }

페이지 넘기기 효과 제거하고 페이지 이동바 표시

    // Attributes inspector > Transition Style Scroll 경우 총페이지 표시
    public func presentationCount(for pageViewController: UIPageViewController) -> Int {
        return vcArray.count
    }
    
    // Attributes inspector > Transition Style Scroll 경우 현재 페이지 표시
    public func presentationIndex(for pageViewController: UIPageViewController) -> Int {
        return 0
    }

페이지 이동바 숨기기

   override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        for subView in view.subviews {
            // subView가 UIScrollView 이면, subView.frame을 전체 크기(UIScreen.main.bounds)로 한다 -> 페이지 넘기는 화면이 사라짐
            if subView is UIScrollView {
                subView.frame = UIScreen.main.bounds
            }
        }
    }

Modal 페이지 띄우기

        if let modalVC = storyboard?.instantiateViewController(withIdentifier: "modalVC") {
            modalVC.modalTransitionStyle = .flipHorizontal
            present(modalVC, animated: true, completion: {
                print("show modal complete")
            })
        }

Modal 페이지 닫기

dismiss(animated: true, completion: nil)

페이지 스텍을 전부 비우고 최상위 페이지로 이동

navigationController?.popToRootViewController(animated: true)

Modal 페이지 띄우기

   @IBAction func showPage4Clicked(_ sender: UIButton) {
        
        if let page4VC = storyboard?.instantiateViewController(withIdentifier: "page4VC") {
            navigationController?.pushViewController(page4VC, animated: true)
        }
    }
    
    @IBAction func showPage7Clicked(_ sender: UIButton) {
        
        let sb = UIStoryboard(name : "main3", bundle : nil)

        let page7VC = sb.instantiateViewController(withIdentifier: "page7VC")
        
        navigationController?.pushViewController(page7VC, animated: true)
        
    }
    
    @IBAction func showPage2Clicked(_ sender: UIButton) {
        
        
        navigationController?.popViewController(animated: true)
    }

    @IBAction func showPage3Clicked(_ sender: UIButton) {
        performSegue(withIdentifier: "showPage3Segue", sender: nil)
    }
저작자 표시
신고

Swift - UIImageView.animationImages

Programming/Swift 2017.06.17 09:47 Posted by 파란크리스마스

출처 : ios - Swift - How to animate Images? - Stack Overflow

//
//  ViewController.swift
//  AniImage
//
//  Created by bluesanta on 2017. 6. 10..
//  Copyright © 2017년 bluesanta. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet weak var indicatorImage: UIImageView!
    
    var imageArray = [UIImage]()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        for i in 1...5 {
            imageArray.append(UIImage(named: String(format : "%02d.png", i))!)
        }
        
        indicatorImage.animationImages = imageArray
        indicatorImage.animationDuration = 0.7
    }

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

    @IBAction func startClicked(_ sender: UIButton) {
        indicatorImage.startAnimating()
    }
    
    @IBAction func stopClicked(_ sender: UIButton) {
        indicatorImage.stopAnimating()
    }
    

}


저작자 표시
신고

Swift tip

Programming/Swift 2017.05.27 10:48 Posted by 파란크리스마스

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()
        }
저작자 표시
신고

Xcode6 / Swift - 동적으로 UILabel, Timer 생성

Programming/Swift 2014.06.04 22:06 Posted by 파란크리스마스

출처 : Swiftでアニメーションとタイマーを使ってみた
Swift for UIButton addTarget
viewDidLoad 와 viewWillAppear의 차이

ViewController.swift 최초 기본 코드

//
//  ViewController.swift
//  CreateLabel
//
//  Created by test on 2014. 6. 5..
//  Copyright (c) 2014년 test. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
                            
    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.
    }
    
}

UILabel class내 전역변수로 추가

var label : UILabel = UILabel();

viewDidLoad 함수에 내용 추가

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        //var label : UILabel = UILabel();
        label.text = "test";
        label.frame = CGRectMake(50, 50, 100, 50);
        self.view.addSubview(label);
    }

실행

Timer 생성

타이머를 추가해서 1초마다 내용이 수정되는 예제

완성된 코드

//
//  ViewController.swift
//  CreateLabel
//
//  Created by test on 2014. 6. 5..
//  Copyright (c) 2014년 test. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    var countNum = 0;
    
    var label : UILabel = UILabel();
                            
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        //var label : UILabel = UILabel();
        label.text = "test";
        label.frame = CGRectMake(50, 50, 100, 50);
        self.view.addSubview(label);
        
        // 타이머 생성
        var timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("update"), userInfo: nil, repeats: true);
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // 1초마다 호출되는 함수
    func update() {
        label.text = String(countNum);
        countNum++;
    }

}

실행

신고

Xcode6 / Swift - Hello World !!!

Programming/Swift 2014.06.03 22:00 Posted by 파란크리스마스

출처 :Welcome to Swift
The Swift Programming Language
The Swift Programming Language(iTunes)
애플 새 개발언어 '스위프트' 이용 10개 팁

변수와 상수

상수 선언 - 키워드 let

let languageName = "Swift"
languageName = "Swift++"
// this is a compile-time error - languageName cannot be changed

변수 선언 - 키워드 var

var friendlyWelcome = "Hello!"
friendlyWelcome = "Bonjour!"
// friendlyWelcome is now "Bonjour!’

전역 로그 출력

print, println 함수 - 자바의 System.out.print, System.out.println 와 동일한 기능으로 xcode 의 output 창에 출력하는 함수 제공

println("This is a string")
// prints "This is a string

주석

한줄 주석 (Single-line) : forward-slashes (//)

// this is a comment

여러줄 주석 (multiline comments) : 주석 시작 (/*) 주석 끝 (*/)

/* this is also a comment,
but written over multiple lines */

- 작성중 -

Xcode6 설치

Xcode 실행

Create a new Xcode project 선택

Single View Application 선택

Language : Swift 선택

Label, Button Control 추가

Label Control 변수로 등록

Label 이름 등록

Button Touch Down 이벤트 추가

Button 이벤트 이름 등록

Hello World 출력

실행


신고


 

티스토리 툴바