준코딩

(ios/Swift)Toast 메시지 띄우기. 본문

프로그래밍/IOS (Swift)

(ios/Swift)Toast 메시지 띄우기.

Ljunhyeob - App Dev 2022. 12. 20. 14:23

Xcode : 14.2v

사용언어: Swift , StoryBoard

깃허브주소: https://github.com/Ljunhyeob/ToastMessage

 

 

1.프로젝트 생성 후 좌측 ViewController 로 이동해서 코드를 작성해줍니다. 

2. 아래와 같이 코드를 작성해주고 viewDidLoad() 안에서 showToast() 함수에다가 원하는 문구를 넣으면 앱이 실행될때 토스트 메시지가 뜨게 됩니다.

(코드에 주석으로 설명 적어놓았습니다.)

import UIKit


class ViewController: UIViewController {


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        showToast(message: "안녕하세요.")  //토스트 메시지 호출하는 부분.
    }
    
    
    func showToast(message : String) {
            let width:CGFloat = 20 // 가로 크기 지정
            let toastLabel = UILabel(frame: CGRect(x: width, y: self.view.frame.size.height-100, width: view.frame.size.width-2*width, height: 50)) // 세로 크기 및 동적 속성 지정
            
            // 뷰가 위치할 위치를 지정
            toastLabel.backgroundColor = UIColor.black.withAlphaComponent(0.6) // 배경 색상
            toastLabel.textColor = UIColor.white // 텍스트 색상
            toastLabel.textAlignment = .center; // 텍스트 정렬
            toastLabel.text = message // 메시지
            toastLabel.alpha = 1.0 // 투명도
            toastLabel.layer.cornerRadius = 10 // 코너 둥글기
            toastLabel.clipsToBounds  =  true //코너 둥글기 활성화
            self.view.addSubview(toastLabel) // 뷰 컨트롤러에 추가
            
            // [애니메이션 동작 실시]
            UIView.animate(withDuration: 4.0, delay: 0.1, options: .curveEaseOut, animations: {
                toastLabel.alpha = 0.0
            }, completion: {(isCompleted) in
                toastLabel.removeFromSuperview() // 뷰컨트롤러에서 제거
            })
        }


}

 

3. 버튼으로 토스트 메세지 띄우는 방법.

좌측 Main으로 가셔서 StoryBoard를 띄워줍니다.

 

4.우측 상단 + 버튼을 누르고 Button을 찾아서 스토리보드위에 드래그 앤 드롭으로 생성해 줍니다.

 

5. 버튼 생성할때 눌렀던 + 버튼 아래에 있는 좌측 정렬같은 버튼을 누르고 Assistant 를 눌러줍니다.

6. 그러면 이렇게 스토리보드와 viewcontroller 가 함께 뜨게 됩니다.

스토리보드에 있는 버튼을 활성화 시킨후(좌클릭 1번) -> 우클릭으로 버튼을 누른 상태에서 viewController로 끌고가서 놓아줍니다.

 

7. 이제 이름을 설정하고 연결해줍니다. (저는 button 으로 해주겠습니다.)

 

8. 생성 하고 나면 viewcontroller 에 코드 한줄이 생성이 됩니다.

이 코드 안에 버튼을 눌렀을때 실행할 코드를 작성해 주시면됩니다.

 

 

9. 처음에 만들었던 showToast 함수를 버튼을 눌렀을때 불러와 주도록 만들면 끝입니다.

 

 

 

최종 소스.

import UIKit


class ViewController: UIViewController {


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        showToast(message: "안녕하세요.")
    }
    
    @IBAction func button(_ sender: Any) {
        showToast(message: "버튼으로 만든 토스트.")
    }
    
    func showToast(message : String) {
            let width:CGFloat = 20 // 가로 크기 지정
            let toastLabel = UILabel(frame: CGRect(x: width, y: self.view.frame.size.height-100, width: view.frame.size.width-2*width, height: 50)) // 세로 크기 및 동적 속성 지정
            
            // 뷰가 위치할 위치를 지정
            toastLabel.backgroundColor = UIColor.black.withAlphaComponent(0.6) // 배경 색상
            toastLabel.textColor = UIColor.white // 텍스트 색상
            toastLabel.textAlignment = .center; // 텍스트 정렬
            toastLabel.text = message // 메시지
            toastLabel.alpha = 1.0 // 투명도
            toastLabel.layer.cornerRadius = 10 // 코너 둥글기
            toastLabel.clipsToBounds  =  true //코너 둥글기 활성화
            self.view.addSubview(toastLabel) // 뷰 컨트롤러에 추가
            
            // [애니메이션 동작 실시]
            UIView.animate(withDuration: 4.0, delay: 0.1, options: .curveEaseOut, animations: {
                toastLabel.alpha = 0.0
            }, completion: {(isCompleted) in
                toastLabel.removeFromSuperview() // 뷰컨트롤러에서 제거
            })
        }


}
Comments