> For the complete documentation index, see [llms.txt](https://pakornpat.gitbook.io/ios-app/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://pakornpat.gitbook.io/ios-app/v2/uiviewcontroller.md).

# UIViewController

## Controller ของหน้าจอ

โดยปกติหน้าจอแต่ละหน้าจอใน Storyboard จะมีโค้ดที่ใช้ในการควบคุมหน้าจอนั้น เพื่อให้หน้าจอแสดงค่า และรับ action ของผู้ใช้ ส่วนนี้เราจะเรียกว่า ViewController&#x20;

ตัวอย่างของ ViewController ที่ Xcode สร้างให้ในตอนแรก

```swift
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
```

## Cycle ของ ViewController

เมื่อ ViewController นั้นถูกเรียกให้แสดงผล ถ้ายังไม่เคยถูกสร้างมาก่อน เมื่อสร้างเสร็จและเชื่อมโยง View ต่าง ๆ เช่น Label, TextField จะเรียก viewDidLoad เมื่อกำลังจะถูกแสดงขึ้นมาจะเรียก viewWillAppear และเมื่อแสดงเสร็จแล้วจะกลายเป็น viewDidAppear

ในขณะที่จะหายไปก็เช่นกัน จะเรียก viewWillDisappear และเมื่อหายไปแล้วก็จะเป็น viewDidDisappear

![](https://144845262-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGk7Utff0rVWsqK4eYO%2F-LGk9LnxWMiKEaH9nX5o%2F-LGkGzKjeR8OZkg5j-2d%2FScreen%20Shot%202018-07-06%20at%2022.48.11.png?alt=media\&token=5b0dc594-ddc5-43cd-b298-bd98159d332d)

{% hint style="info" %}
สามารถอ่านเพิ่มเติมเกี่ยวกับเรื่องนี้ได้ที่\
[Handling View-Related Notifications](https://developer.apple.com/documentation/uikit/uiviewcontroller)
{% endhint %}
