Swift 정리 - (2)

init·2022년 3월 19일
0

ImageView

코드

import UIKit

class ViewController: UIViewController {

    var isZoom = true
    var imgOn : UIImage?
    var imgOff : UIImage?
    
    @IBOutlet var imgView: UIImageView!
    @IBOutlet var btnResize: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        imgOn = UIImage(named:"lamp_on.png")
        imgOff = UIImage(named:"lamp_off.png")
        
        imgView.image = imgOn
    }
    @IBAction func btnResizeImg(_ sender: UIButton) {
        let scale:CGFloat = 2.0
        var newWidth:CGFloat, newHeight :CGFloat
        
        if (isZoom){
        
            newWidth = imgView.frame.width/scale
            newHeight = imgView.frame.height/scale
            btnResize.setTitle("확대", for: .normal)
            
        }
        else {
        
            newWidth = imgView.frame.width*scale
            newHeight = imgView.frame.height*scale
            btnResize.setTitle("축소", for: .normal)
            
        }
        imgView.frame.size = CGSize(width:newWidth,height:newHeight)
        isZoom = !isZoom
    }
    @IBAction func switchImageOnOff(_ sender: UISwitch) {
        if sender.isOn {
            imgView.image = imgOn
        }else {
            imgView.image = imgOff
        }
    }
}

문법

옵셔널 변수

옵셔널 변수란 변수가 nil이거나 값의 존재 여부를 알 수 없는 것을 의미한다.

  • 위 코드에서는 변수 imgOn을 선언했는데 초깃값을 주지 않았기 때문에 '값이 없을 수 있다' 는 의미로 ? 를 붙여 주어야 한다.
  • 위와 같이 옵셔널로 선언된 변수에 값이 할당되면 그 값은 '옵셔널이 래핑되었다'고 하며, !를 사용하여 강제 언래핑이 가능하다.

CGFloat

CGFloat 는 Xcode에서 Float 를 재정의한 자료형

코드

@IBAction func btnResizeImg(_ sender: UIButton) {
        let scale:CGFloat = 2.0
        var newWidth:CGFloat, newHeight :CGFloat

viewDidLoad() 함수란?

만든 뷰를 불러왔을 때 호출되는 함수로, 실행하고자 하는 기능이 필요할 때 사용 가능하다.

코드

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        imgOn = UIImage(named:"lamp_on.png")
        imgOff = UIImage(named:"lamp_off.png")
        
        imgView.image = imgOn
    }

UIViewController -- <추가 공부 필요!!>

도구 모음, 탐색 모음 및 응용프로그램 보기에 대한 보기 관리 기능을 제공합니다.
또한 UIViewController 클래스는 장치 방향이 변경될 때 모달 보기 및 회전 보기를 지원합니다.
(참고: https://velog.io/@wook4506/iOS-Swift-Storyboard와-ViewController)

class ViewController: UIViewController {

    var isZoom = true
    var imgOn : UIImage?
    var imgOff : UIImage?
    
    @IBOutlet var imgView: UIImageView!
    @IBOutlet var btnResize: UIButton!
  • 즉, 말그대로 뷰를 개발자 마음대로 설정하기 위한 클래스다.
profile
iOS,android 개발 공부를 하고 있습니다

0개의 댓글

관련 채용 정보