ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Swift 피커 뷰 사용해서 원하는 항목 선택하기
    swift 2024. 10. 13. 15:16
    반응형

     

    특정 이미지들을 파일 경로에 추가해준다.

    images/ 이미지들 

     

    특정 메서드들을 이용하기 위해

    UIPickerViewDelegate, UIPickerViewDataSource 를 상속해 준다

    import UIKit
    
    class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
        let MAX_ARRAY_NUM = 10
        let PICKER_VIEW_COLUMN = 1
        let PICKER_VIEW_HEIGHT:CGFloat = 80
        var imageArray = [UIImage?]()
        var imageFileName = [ "1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg",
                              "6.jpg", "7.jpg", "8.jpg", "9.jpg", "10.jpg" ]
    
        @IBOutlet var pickerImage: UIPickerView!
        @IBOutlet var lblImageFileName: UILabel!
        @IBOutlet var imageView: UIImageView!
        
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view.
    
    		// 뷰가 로드 될떄 MAX_ARRAY_NUM 개수만큼 imageFileName에 있는 이미지를 할당항
            // 처음 로드될때 0번쨰 배열에 있는 이미지를 넣어준다.
            for i in 0 ..< MAX_ARRAY_NUM {
                let image = UIImage(named: imageFileName[i])
                imageArray.append(image)
            }
            
            lblImageFileName.text = imageFileName[0]
            imageView.image = imageArray[0]
        }
    
        // returns the number of 'columns' to display.
        func numberOfComponents(in pickerView: UIPickerView) -> Int {
            return PICKER_VIEW_COLUMN
        }
        
        // returns height of row for each component.
        func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
            return PICKER_VIEW_HEIGHT
        }
    
        // returns the # of rows in each component..
        func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
            return imageFileName.count
        }
        
    //    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    //        return imageFileName[row]
    //    }
    
        func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
            let imageView = UIImageView(image:imageArray[row])
            imageView.frame = CGRect(x: 0, y: 0, width: 100, height: 150)
            
            return imageView
        }
    
        func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
            lblImageFileName.text = imageFileName[row]
            imageView.image = imageArray[row]
        }
    }

     

    반응형

    'swift' 카테고리의 다른 글

    Swift 지도 만들기 Map View  (0) 2024.11.23
    swift present 메서드  (0) 2024.10.26
    unrecognized selector sent to instance  (1) 2024.10.26
    Swift 알람 시계 만들기  (2) 2024.10.13
    swift 정리 1  (0) 2023.07.16

    댓글

Designed by Tistory.