Swift: Implement a Custom Control


Swift: Implement a Custom Control

Create a View

You typically create a view in one of two ways: by initializing the view with a frame so that you can manually add the view to your UI, or by allowing the view to be loaded by the storyboard. There’s a corresponding initializer for each approach: <code class="code-voice">init(frame:) for the frame and <code class="code-voice">init?(coder:) for the storyboard. Recall that an initializer is a method that prepares an instance of a class for use, which involves setting an initial value for each property and performing any other setup.


Property Observer

property observer observes and responds to changes in a property’s value. Property observers are called every time a property’s value is set, and can be used to perform work immediately before or after the value changes. Specifically, the <code class="code-voice">didSet property observer is called immediately after the property’s value is set.

Property observer对一个property的值进行观测并作出响应。只要property的值发生变化,property observer就会被调用,并且可以指定是在值变化前还是变化后进行。didset property observer在property的值发生变化后被立即调用。