<span id="Label3"></p><p><p><em>Note: I am a translator, and add a bit of my opinion.</em></p></p><p><p><span style="font-size: medium;"><strong>Objective</strong></span></p></p><p><p>This article discusses some of the tips and tricks of custom views, Controls. Let's outline the controls that UIKit provides to us, and introduce some rendering Techniques. We then delve into the communication strategy between the view and its owner, and briefly explore accessibility, localization, and Testing.</p></p><p><p><span style="font-size: medium;"><strong>Directory</strong></span></p></p><p><p>1. View Hierarchy Overview<br>2. rendering<br>3. Custom Drawing<br>4. Custom Interactions<br>5. Using Target-action<br>6. Using proxies<br>7. Use Block<br>8. Using KVO<br>9. Use Notifications<br>10. Auxiliary Function (accessibility)<br>11. Localization<br>12. Testing</p></p><span style="font-size: medium;"><span style="font-size: medium;">1. View Hierarchy Overview</span></span><p><p>If you look at a subclass of UIView, you can find 3 base classes: <span style="text-decoration: underline;"> <code>reponders</code> (responder), <code>views</code> (view), and <code>controls</code> (control)</span>. Let's take a quick look at what's going on between Them.</p></p><p><p><strong><span style="font-size: small;">1) Uiresponder</span></strong></p></p><p><p><code> <span style="text-decoration: underline;"> UIResponder</span></code><span style="text-decoration: underline;">is <code>UIView</code> the parent class</span> . <span style="text-decoration: underline;"> <code>responder</code> ability to handle events such as touch, gesture, remote control</span> , and More. The reason why it is a separate class is not merged into <code>UIView</code> , because <code>UIResponder</code> there are more subclasses, the most obvious is <code>UIApplication</code> and <code>UIViewController</code> . <span style="text-decoration: underline;">by overriding <code>UIResponder</code> the method, you can decide whether a class can be the first responder (responder), which is the current input focus element</span> .</p></p><p><p>when <span style="text-decoration: underline;">interactive behaviors such as touches (touch) or motion (a series of motion Sensors) occur, They are sent to the first responder (usually a view)</span>. <span style="text-decoration: underline;">If the first responder does not handle the behavior, it reaches the view controller Uiviewcontroller along the response chain and continues to be passed to the app if the behavior is still not processed</span> . If you want to monitor the shaking gesture, you can handle it anywhere in the 3 layers as Needed.</p></p><p><p><code> UIResponder</code>It also allows you to customize the input method, from <code>inputAccessoryView</code> Adding a secondary view to the keyboard to using <code>inputView</code> a fully customizable Keyboard.</p></p><p><p><strong><span style="font-size: small;">2) UIView</span></strong></p></p><p><p><code> <span style="text-decoration: underline;">UIView</span></code><span style="text-decoration: underline;">subclasses handle all things related to content rendering and touch time</span> . As long as people who have written "Hello, world" apps know the view, but we reiterate some tips:</p></p><p><p>A common error concept: the area of the view is defined by its Frame. In fact <span style="text-decoration: underline;">, frame is a derived property that is composed of <code>center</code> and <code>bounds</code> synthesized from</span> . When you do not use Auto Layout, most people use frame to change the position and size of the VIEW. Be careful, official documents specify a particular note:</p></p> <blockquote> <blockquote> <p>If the Transform property is not an identity transform, then the value of this property is undefined, so it should be ignored</p> </blockquote> </blockquote><p><p>Another way to allow you to add interactivity to a view is to use gesture Recognition. Note that they do not work on responders, but only on the view and its subclasses.</p></p><p><p><strong><span style="font-size: small;">3) Uicontrol</span></strong></p></p><p><p><code> <span style="text-decoration: underline;">UIControl</span></code><span style="text-decoration: underline;">built on the view, adding more interactive Support. Most importantly, it adds the target/action mode</span> . To look at the specific subclass, we can look at the button, the date selector (day pickers), the text box, and so On. When creating interactive controls, you typically want to subclass one <code>UIControl</code> . Some common classes like bar buttons (although also supporting Target/action) and text view (where you need to use proxies to get Notifications) are actually not <code>UIControl</code> .</p></p><p><p></p></p><p><p><span style="font-size: medium;"><strong>2. rendering</strong></span></p></p><p><p>Now we turn to the visible part: custom Rendering. As Daniel mentions in his article, you might want to avoid rendering on the CPU and throwing it to the GPU. Here's an experience: try to avoid <code>drawRect:</code> using an existing view to build a custom VIEW.</p></p><p><p>Usually the quickest way to render is to use the picture View. For example, Suppose you want to draw a circular avatar with a border, as in the following image:</p></p><p><p></p></p><p><p>To achieve this, we created a subclass of the picture view with the following code:</p></p><pre><pre><span style="color: #008000;">//</span> <span style="color: #008000;">called from initializer</span>-(<span style="color: #0000ff;">void</span><span style="color: #000000;">) setupview{ </span>=<span style="color: #000000;"> YES; </span> <span style="color: #800080;">2</span> <span style="color: #000000;">; </span> <span style="color: #800080;">3</span> <span style="color: #000000;">; </span> =<span style="color: #000000;"> [uicolor darkgraycolor]. cgcolor;}</span></pre></pre><p><p>I encourage readers to understand <code>CALayer</code> their properties, because most of the things you can do with it will be faster than drawing yourself with the Core Graphics. however, as always, it is important to monitor the performance of your own Code.</p></p><p><p>The use of stretched images and picture views can also greatly improve Efficiency. In taming UIButton this post, Reda Lemeden explored several different methods of Drawing. At the end of the article, there is a valuable response from Andy matuschak, an engineer from the UIKit team, explaining that the stretchable picture is the fastest of these Technologies. The reason is that the stretched picture has the least amount of data transfer between the CPU and the GPU, and the drawing of these pictures is highly optimized.</p></p><p><p>When working with pictures, you can also let the GPU work for you instead of using the Core Graphics. With Core image, You can create complex effects on a picture without having to do any work with the CPU. You can render directly on the OpenGL context, and all the work is done on the GPU.</p></p><p><p></p></p><p><p><span style="font-size: medium;"><strong>3. Custom Drawing</strong></span></p></p><p><p>If you decide to use custom drawing, there are several different options to choose From. If possible, see if you can generate a picture and cache it on memory and on Disk. If the content is dynamic, maybe you can use the core Animation, if it doesn't work, use the core Graphics. If you really want to get close to the bottom, it's not that hard to use glkit and native OpenGL, but you need to do a lot of Work.</p></p><p><p>If you really chose <code>drawRect:</code> to rewrite, make sure to check the content Mode. The default mode is to scale the content to fill the extent of the view, which is not redrawn when the frame of the view Changes.</p></p><p><p></p></p><p><p><strong><span style="font-size: medium;">4. Custom Interactions</span></strong></p></p><p><p>As previously stated, you will almost certainly extend a uicontrol subclass when customizing the Control. In your subclass, you can use the target action mechanism to trigger events, such as the following example:</p></p><pre><pre>[self sendactionsforcontrolevents:uicontroleventvaluechanged];</pre></pre><p><p>To respond to touch, you may be more inclined to use gesture Recognition. however, If you want to be closer to the bottom, you can still rewrite <code>touchesBegan</code> , <code>touchesMoved</code> and <code>touchesEnded</code> method to access the original touch Behavior. But even so, creating a subclass of gesture recognition to separate gesture-processing-related logic from your view or view controller can be a more appropriate approach in many Cases.</p></p><p><p>A common design problem when creating custom controls is to return the returned value to the class that owns Them. For example, Suppose you create a custom control that draws an interactive pie chart, and you want to know when a user chooses one of the Sections. You can solve this problem in many different ways, such as through target action mode, proxy, block or KVO, or even Notification.</p></p><p><p></p></p><p><p><strong><span style="font-size: medium;">5. Using Target-action</span></strong></p></p><p><p>Classic College school, usually the most convenient way is to use Target-action. After the user chooses, you can do something like this in a custom view:</p></p><pre><pre>[self sendactionsforcontrolevents:uicontroleventvaluechanged];</pre></pre><p><p>If you have a view controller that manages this view, you need to do this:</p></p><pre><pre>-(<span style="color: #0000ff;">void</span><span style="color: #000000;">) setuppiechart{ [self.piechart addtarget:self action: @selector (updateselection:) forcontrolevents:uicontroleventvaluechanged];}</span> -(<span style="color: #0000ff;">void</span>) updateselection: (<span style="color: #0000ff;">ID</span><span style="color: #000000;">) sender{ NSLog (</span><span style="color: #800000;">@ "</span><span style="color: #800000;">%@</span><span style="color: #800000;">"</span> <span style="color: #000000;">, self.pieChart.selectedSector);}</span></pre></pre><p><p>The advantage of doing this is that there are few things to do in a custom view subclass and that you get multi-target support automatically.</p></p><p><p></p></p><p><p><strong><span style="font-size: medium;">6. Using proxies</span></strong></p></p><p><p>If you need more control over the messages sent from the view to the view controller, you typically use proxy Mode. In our pie chart, the code looks like This:</p></p><pre><pre>[self. <span style="color: #0000ff;">Delegate</span> piechart:self didSelectSector:self.selectedSector];</pre></pre><p><p>In the view controller, you write the following code:</p></p><pre><pre><span style="color: #0000ff;">@interface</span> Myviewcontroller <PieChartDelegate><span style="color: #000000;"> </span> ... -(<span style="color: #0000ff;">void</span><span style="color: #000000;">) setuppiechart{ self.piechart.</span> <span style="color: #0000ff;">delegate</span> = self<span style="color: #000000;"> ;}</span> -(<span style="color: #0000ff;">void</span>) piechart: (piechart*) piechart didselectsector: (piechartsector*<span style="color: #000000;">) sector{ </span><span style="color: #008000;">// </span> <span style="color: #008000;">processing Chunks</span> }</pre></pre><p><p>This is obviously more appropriate when you want to do more complex work rather than just informing the owner that the value has Changed. But while most developers can implement custom proxies very quickly, there are some drawbacks to this approach: you have to check that the proxy implements the method you want to invoke (using <code>respondsToSelector:</code> ), and most importantly, usually you have only one proxy (or you need to create an array of proxies). In other words, once communication between the view owner and the view becomes slightly more complex, we will almost always take this pattern.</p></p><p><p></p></p><p><p><span style="font-size: medium;"><strong>7. Use Block</strong></span></p></p><p><p>Another option is to use BLOCK. Once again, with a pie chart example, the code looks like This:</p></p><pre><pre><span style="color: #0000ff;">@interface</span><span style="color: #000000;"></span><span style="color: #0000ff;">void</span>(^selectionhandler) (piechartsection*<span style="color: #000000;"> selectedsection);</span> <span style="color: #0000ff;">@end</span></pre></pre><p><p>In the code that selects the behavior, you only need to execute it. It is important to check if block is assigned before this, because executing a block that is not assigned will cause the program to Crash.</p></p><pre><pre><span style="color: #0000ff;">if</span> (self.selectionhandler! =<span style="color: #000000;"> NULL) { self.selectionhandler (self.selectedsection);}</span></pre></pre><p><p>The benefit of this approach is that the relevant code can be integrated in the view Controller:</p></p><pre><pre>-(<span style="color: #0000ff;">void</span><span style="color: #000000;">) setuppiechart{ </span>= ^ (piechartsection* section<span style="color: #000000;"> ) { </span><span style="color: #008000;">//</span> <span style="color: #008000;"> processing block</span> <span style="color: #000000;"> }}</span></pre></pre><p><p>Just like an agent, each action usually has only one block. Another important limitation is not to form a reference loop. If your view controller holds a strong reference to a pie chart, the pie chart holds the Block,block and holds the view controller, forming a reference loop. This error can be caused by referencing self in the BLOCK. So the code is usually written like this:</p></p><pre><pre><span style="color: #0000ff;">ID</span> weakself =<span style="color: #000000;"></span>= ^ (piechartsection* section<span style="color: #000000;"> ) { myviewcontroller</span>* strongself = <span style="color: #000000;"> weakself; [strongself handlesectionchange:section];}</span></pre></pre><p><p>Once the code in the block is out of control (for example, There are too many things to do in block, which leads to too much code in the block), you should also pull them out into separate ways, which might be better with proxies.</p></p><p><p></p></p><p><p><span style="font-size: medium;"><strong>8. Using KVO</strong></span></p></p><p><p>If you like KVO, you can also use it to Observe. This is a bit magical and not so straightforward, but when used in applications, it is a good decoupling design pattern. In the pie chart class, write the Code:</p></p><pre><pre>Self.selectedsegment = thenewselectedsegment;</pre></pre><p><p>When the composition attribute is used, KVO will intercept the change and issue a Notification. In the view controller, write a similar code:</p></p><pre>- (<span style="color: #0000ff;"><span style="color: #0000ff;">void</span></span><span style="color: #000000;"><span style="color: #000000;">) Setuppiechart{[self.piechart addobserver:self forkeypath:</span></span><span style="color: #800000;"><span style="color: #800000;">@"</span></span><span style="color: #800000;"><span style="color: #800000;">selectedsegment</span></span><span style="color: #800000;"><span style="color: #800000;">"</span></span>Options<span style="color: #800080;"><span style="color: #800080;">0</span></span><span style="color: #000000;"><span style="color: #000000;">context:null];}</span></span>- (<span style="color: #0000ff;"><span style="color: #0000ff;">void</span></span>) observevalueforkeypath: (nsstring *) keypath ofobject: (<span style="color: #0000ff;"><span style="color: #0000ff;">ID</span></span>)<span style="color: #0000ff;"><span style="color: #0000ff;">Object</span></span>Change: (nsdictionary *) Change Context: (<span style="color: #0000ff;"><span style="color: #0000ff;">void</span></span>*<span style="color: #000000;"><span style="color: #000000;">) Context {</span></span><span style="color: #0000ff;"><span style="color: #0000ff;">if</span></span>(<span style="color: #0000ff;"><span style="color: #0000ff;">Object</span></span>= = Self.piechart && [keypath isequaltostring:<span style="color: #800000;"><span style="color: #800000;">@"</span></span><span style="color: #800000;"><span style="color: #800000;">selectedsegment</span></span><span style="color: #800000;"><span style="color: #800000;">"</span></span><span style="color: #000000;"><span style="color: #000000;">]) { </span></span><span style="color: #008000;"><span style="color: #008000;">//</span></span><span style="color: #008000;"><span style="color: #008000;">Handling Changes</span></span><span style="color: #000000;"><span style="color: #000000;"> }}</span></span></pre><p><p>Depending on your needs, you <code>viewWillDisappear:</code> will <code>dealloc</code> need to remove the viewer in Or. Setting multiple observers on the same object can easily cause Confusion. There are some techniques to solve this problem, such as Reactivecocoa or more lightweight <code>THObserversAndBinders</code> .</p></p><p><p></p></p><span style="font-size: medium;"><span style="font-size: medium;">9. Use Notifications</span></span><p><p>As a last option, if you want a very loose coupling, you can use notifications to make other objects aware of the Changes. For pie charts You almost certainly don't want to do this, but for the sake of completeness, here's how to do it. In the header file of the pie chart:</p></p><pre><pre><span style="color: #0000ff;">extern</span> <span style="color: #0000ff;">Const</span> selectedsegmentchangednotification;</pre></pre><p><p>In the implementation file:</p></p><pre><pre><span style="color: #0000ff;">Const</span> <span style="color: #800000;">@"</span> <span style="color: #800000;">selectedsegmentchangednotification</span> <span style="color: #800000;">"</span> <span style="color: #000000;">;...</span> -(<span style="color: #0000ff;">void</span><span style="color: #000000;">) notifyaboutchanges{ </span><span style="color: #0000ff;">object</span><span style="color: #000000;">: self];}</span></pre></pre><p><p>Subscribe now to notifications in the view Controller:</p></p><pre><pre>-(<span style="color: #0000ff;">void</span><span style="color: #000000;">) setuppiechart{ [[nsnotificationcenter defaultcenter] addobserver:self selector:@ Selector (segmentchanged:) name:selectedsegmentchangednotification </span><span style="color: #0000ff;">object</span><span style="color: #000000;">: self.piechart];} ...</span> -(<span style="color: #0000ff;">void</span>) segmentchanged: (nsnotification*<span style="color: #000000;">) note{}</span></pre></pre><p><p>When you add an observer, you can instead pass the pie chart as an argument <code>object</code> , <code>nil</code> to receive notifications from all Pie-chart Objects. Just like KVO notice, you also need to unsubscribe from these notices in the right place.</p></p><p><p>The benefit of this technique is complete decoupling. On the other hand, you lose type safety because you get a notification object in the callback, and unlike the proxy, the compiler cannot check whether the type matches between the sender and Receiver.</p></p><p><p></p></p><p><p><span style="font-size: medium;"><strong>10. Auxiliary Function (accessibility)</strong></span></p></p><p><p>The standard IOS controls provided by Apple all have accessibility features. This is another reason to recommend creating custom controls with standard Controls.</p></p><p><p>This may be a full-time theme, but if you want to write a custom view, The Accessibility Programming Guide shows you how to create a secondary controller. Most notably, if there are multiple elements in a view that require accessibility, but they are not child views of the view, you can have the view implement the <code>UIAccessibilityContainer</code> Protocol. For each element, returns an object that describes it <code>UIAccessibilityElement</code> .</p></p><p><p></p></p><p><p><strong><span style="font-size: medium;">11. Localization</span></strong></p></p><p><p>Localization is just as important when creating custom Views. Like accessibility, This can be a full-time topic. The most straightforward task of localizing a custom view is the string content. If you use it <code>NSString</code> , you don't have to worry about coding Problems. If you are displaying dates or numbers in a custom view, use date and number formatting classes to show Them. Use <code>NSLocalizedString</code> localized strings.</p></p><p><p>Another useful tool in the localization process is Auto Layout. For example, having a short word in English can be very long in German. If the size of the view is hard-coded according to the length of the English word, it will almost certainly be troublesome when translated into German. By using auto Layout, the Label control automatically adjusts to the dimensions of the content and adds some additional restrictions to the dependent elements to ensure that the dimensions are resized so that the work becomes very simple. Apple provides a good introduction to This. also, for a right-to-left language like hebrew, if you use the leading and trailing properties, the entire view is automatically displayed in a right-to-left order instead of hard-coded left-to-right.</p></p><p><p></p></p><p><p><strong><span style="font-size: medium;">12. Testing</span></strong></p></p><p><p>finally, Let's consider the problem of testing the VIEW. For unit testing, You can use Xcode's own tools or other Third-party frameworks. In addition, you can use UIAutomation or other tools based on it. For this reason, it is necessary for your view to fully support Accessibility. A function that uiautomation is not fully utilized; you can use it to automatically compare views and designs to make sure that each pixel is exactly. (plug in an unrelated tip: you can also use it to automatically generate apps on the app store, which is especially useful if you have multiple languages in your app).</p></p><p><p>IOS UIView 04-custom Controls</p></p></span>
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