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.

创建view的两种方法:采用frame来初始化一个view以便手动将它添加到UI;或者允许该view被storyboard加载。通常你会选择这两种方法中的一种。两种方法也有各自对应的初始化方法:init(frame:)与init?(coder:)。还记得initializer是将一个类型实例化以便使用的方法,它负责给各个property赋初值并且执行必要的配置操作。

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的值发生变化后被立即调用。