Create a self-registered Swift UI control

Source: Internet
Author: User

Create a self-registered Swift UI control

For custom controls, how do I respond to Event Notifications without disrupting the original message mechanism? In this article, I will demonstrate a notification proxy class. Through a simple example, we use this class to add our new features to the existing iOS UI controls: add placeholder Text to the Text View control.
Problem: Missing Placeholder

Placeholder text is a good method for prompting users to enter the specified type of data in some controls. The placeholder attribute of the UITextField control of UIKit is used to do this. For example, in the Twitter option settings, the User Name field uses the placeholder text. With this placeholder text, you can know that you should enter a Twitter user name containing the @ symbol here. The placeholder text in the Password field indicates that this field is required.







Figure 1-set the Placeholder text in the program

Although Text Filed has the placeholder attribute, its sibling control Text View does not have this attribute.

Problem Solving

I am going to solve this problem like this:

Create a UITextView extension and add a placeholder computing attribute to the extension. When TextView does not enter any text, a Label is displayed. If the input has text, this Label is hidden.

As I mentioned in the previous article, I prefer to use extensions instead of subclasses. Because the extension allows me to use the "outside the box" UIKit control in the App. All I need to do is add a class extension file to the project, and then the class will automatically obtain new features.

Method 1: UITextViewDelegate

When users input text in TextView, iOS has several notification App methods. One of them is through the UITextViewDelegate protocol. In this extension, a reference to TextView is stored in its own delegate attribute. When you enter or delete characters, the TextView protocol method is called. We can add the code to hide and display the placeholder label in the Protocol method.

The disadvantage of this solution is that Text View is too dependent on the delegate attribute, because in a UIControl, you can only register one delegate object. If you need to add more delegate objects to TextView, you will be more troublesome.

Method 2: nsicationicationcenter

Nsicationicationcenter uses the UITextViewTextDidChangeNotification notification to notify you that some characters have been entered or deleted in TextView. This is a better choice because it no longer depends on the delegate attribute. The disadvantage is that you need to log out from the notification center. Generally, we deregister the object from nsicationicationcenter in the deinit method of the object. However, in Swift, we cannot use the deinit method in extensions. So how can we break through this restriction?

Create a notification proxy

We create a lightweight proxy object to break through this restriction. This proxy object replaces TextView to register with the notification center.

I have created a UITextView extension and a proxy class in my project. You can download it from here.

Double-click the. xcodeproj file and use Xcode to open the project. Select the mmTextViewExtensions. swift file in the project navigation window. You can find the notification proxy class (as you can see, it also contains the mmDyamicTypeExtensions class in the previous article ).

The following is the notification proxy class in the file header:

As you can see, it is a subclass of UIView. In this way, we can add it as a subview to TextView. AddObserverForName: usingBLock: the method in the method notification center has the same signature. There is only one line of code in this method, that is, registering TextView to the notification center and passing the parameters, including the closure of TextView, so that the closure is executed when a notification occurs. The notification center will return an NSObjectProtocol object, which will be used to cancel the notification later.

The deinit method only has one line of code. It only cancels an object from the notification center.

The notification proxy class can be reused. You can use it for any type of notifications and any type of objects you want to receive notifications.

Then there is the extension of UITextView. There is a placeholderLabel attribute in the extension. as you think, it references a placeholder label object.

In addition, there is a placeholder string attribute. Later, you will see that all miracles will occur at run time. When the placeholder attribute is set, the code for this calculation attribute will be executed.

Open the Main. storyboard file. 2. There is only one Scene in the story board, and there is a Text View at the top of the Scene.


Figure 2-the main scene contains a text view

When you select Text View and open the properties panel, you will see a Placeholder attribute, which is an attribute added in the extension. The default value of this attribute is "Enter your text here !". This section of text is not displayed at design time (it takes a lot of work to be visible at design time, so this is not the topic of this Article), but it will be displayed at runtime.

The Notification Proxy at Run Time Notification Proxy

The UML sequence diagram in Figure 3 shows the order in which messages are transmitted between all objects.

Figure 3-sequence of message passing between objects during running

Each step is explained as follows:

When the placeholder text of UITextView is changed during running, the code in the extended placeholder calculation attribute is triggered. The extended addPlaceholderLabel method is called. The addPlaceholderLabel method creates a placeholder label and sets the label text. The placeholder label is added to UITextView. A notification proxy object is created. Extend the addObserverForName: withBlock: Method of the Call Notification proxy, and specify that you are interested in the UITextViewTextDidChangeNotification notification. In addition, the closure code will be executed when a notification occurs. The notification proxy object registers UITextView to the notification center and transmits the notification time to TextView. When a notification occurs, the UITextView closure code is executed. UITextView adds a notification proxy object in subview mode. When a UITextViewTextDidChangeNotification notification occurs, the notification center calls the closure of the TextView extension. The UITextView extension sets the hidden attribute of the placeholder label to true and false, depending on whether the text in TextView has content.
11. When TextView is reconstructed at runtime, both the placeholder tag and the notification proxy object are reconstructed. When the notification proxy object is reconstructed, the TextView object is deregistered from the notification center. Let's Take it for a Test Run! Run the test

In Xcode's Scheme control, select one of the simulators such as iPhone 6.
In the Scheme drop-down list of Xcode, select a simulator, such as iPhone 6.

Click Xcode's Run button.
Click Run IN Xcode.

When the app appears in the Simulator, you can see the placeholder text (Figure 4 ).
After the App runs in the simulator, we can see the placeholder text (figure 4 ).

Figure 4-placeholder text at runtime

4. Now type some code in the text view. As soon as you begin typing, the placeholder label disappears (Figure 5). Enter any character in TextView. In this case, placeholder disappears (figure 5 ).

Figure 5-The placeholder text disappears

If you delete the entered characters, the placeholder text will appear again.

Conclusion

There are many ways to solve programming problems. The best way is to take a look at your current selection and analyze the advantages and disadvantages one by one. I hope you can see the benefits of sequence diagrams in this article. It allows you to draw interaction between objects at runtime. I also used this method when writing code. You will find that they can help you find potential problems and help you find new and more efficient solutions to programming problems.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.