티스토리 뷰

Mobile/ios

[ios] ios 8: Page Control

춘햄 2022. 12. 17. 13:16

페이지 컨트롤은 여러 개의 내용을 페이지별로 보여주기 위해 사용하는 객체이다.

 

보통 아이폰에서 아래 쪽으로 작은 동그라미가 줄지어 있는 형태로 많이 사용되며, 이번 포스팅에서는 간단하게 페이지 컨트롤을 활용하여 이미지를 각 페이지에 나타내는 예제를 해보려고 한다.

 

바로 코드와 함께 보자.


우선, 스토리보드는 다음과 같이 이미지 뷰 하나와 하단에 페이지 컨트롤을 둔 간단한 형태로 구성한다.


코드 또한 굉장히 간단하다.

 

이미지의 이름이 들어가 있는 배열을 하나 생성하고, 페이지 컨트롤의 액션 함수가 페이지 번호에 따른 이미지를 이미지 뷰에 삽입하는 형태이다.

 

import UIKit

class ViewController: UIViewController {
    
    var images = ["01.png", "02.png", "03.png", "04.png", "05.png", "06.png",]
    
    @IBOutlet var myImageView: UIImageView!
    @IBOutlet var myPageView: UIPageControl!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        myPageView.numberOfPages = images.count
        myPageView.currentPage = 0
        myPageView.pageIndicatorTintColor = UIColor.green
        myPageView.currentPageIndicatorTintColor = UIColor.red
        
        myImageView.image = UIImage(named: images[0])
        // Do any additional setup after loading the view.
    }
    
    @IBAction func pageControlAction(_ sender: UIPageControl) {
        myImageView.image = UIImage(named: images[myPageView.currentPage])
    }


}

 

이렇게 구성하면, 아래와 같이 페이지 컨트롤의 양 옆을 터치할 때마다 다음/이전 이미지로 이미지 뷰가 채워지는 것을 확인할 수 있다.

 

페이지를 옆으로 넘기는 스와이프 기능은 따로 구현하지 않았기 때문에 코드도 굉장히 심플하여 따로 추가할 건 없다.


 

 

끝!

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

[ios] ios 10: Navigation Controller  (0) 2022.12.19
[ios] ios 9: Tab Bar  (0) 2022.12.17
[ios] ios 7: MapView  (0) 2022.12.15
[ios] ios 6: webView  (0) 2022.12.15
[ios] ios 5: Alert  (0) 2022.12.13
Comments