티스토리 뷰

Mobile/ios

[ios] ios 2: ImageView

춘햄 2022. 12. 12. 18:04

기본적인 ImageView의 사용을 훓어보려고 한다.

 

예제는 하나의 이미지 뷰에 2장의 사진을 switch로 변경 가능하고, "확대" 버튼을 누르면 사진의 크기가 2배 커지도록 동작하는 예제를 실습해보려고 한다.

 

바로 들어가보자.


우선, 스토리보드는 아래와 같이 구성한다.

각 엘리먼트를 swift 객체와 연결한 뒤에 아래와 같이 사진 크기를 조절할 확대 버튼 이벤트 메서드와 switch on, off 에 따른 이벤트 메서드를 추가하면 끝이다.

//
//  ViewController.swift
//  example_project2
//
//  Created by choonham on 2022/12/12.
//

import UIKit

class ViewController: UIViewController {
    var isZoom = false
    var imgOn: UIImage?
    var imgOff: UIImage?
    
    @IBOutlet var imageView_1: UIImageView!
    @IBOutlet var zoomUpButton: UIButton!
    @IBOutlet var turnOnAndOff: UISwitch!

    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")
        
        imageView_1.image = imgOn
    }

    @IBAction func btnZoomAct(_ sender: UIButton) {
        let scale: CGFloat = 2.0
        var newWidth: CGFloat, newHeight: CGFloat
        
        if(isZoom) {
            newWidth = imageView_1.frame.width / scale
            newHeight = imageView_1.frame.height / scale
            
            zoomUpButton.setTitle("확대", for: .normal)
        } else {
            newWidth = imageView_1.frame.width * scale
            newHeight = imageView_1.frame.height * scale
            
            zoomUpButton.setTitle("축소", for: .normal)
        }
        
        imageView_1.frame.size = CGSize(width: newWidth, height: newHeight)
        isZoom = !isZoom
    }
    
    @IBAction func swichOnAndOff(_ sender: UISwitch) {
        if sender.isOn {
            imageView_1.image = imgOn
        } else {
            imageView_1.image = imgOff
        }
    }
    
}

 

'Mobile > ios' 카테고리의 다른 글

[ios] ios 4: Picker View  (0) 2022.12.13
[ios] ios 3: DatePicker & Timer  (0) 2022.12.13
[ios] ios 1: Hello, Swift!  (0) 2022.12.12
[ios] swift 기본 문법 정리 21: 접근 제어  (0) 2022.12.10
[ios] swift 기본 문법 정리 20: Generics  (0) 2022.12.09
Comments