"View Layer" interface drawing

Source: Internet
Author: User

"References":http://www.jianshu.com/p/c5fc8c6b967a

"View Layer" iOS Pure Code Drawing Interface (i)

Word Count 2303 read 385 comments 2 likes 16

The interface drawing in iOS development takes up most of the work, and you can now customize the required interface using STORYBOARD,XIB and code three ways. In these three ways the code is the most flexible and most scalable, and especially in large projects where many people work together, storyboard,xib is not conducive to code merging.
Next, we summarize the interface development of the previous objective.

    • Uiviewcontroller and important sub-categories
      • Uinavigationcontroller
    • UIView and important sub-categories
      • Uicontrol
      • Uiscrollview
    • Attention points for various common controls (follow-up introduction)
    • Apply constraint Masonry library (follow-up introduction)
    • Common Code Snippet (follow-up introduction)
Uiviewcontroller and important sub-categories

Uinavigationcontroller
The most commonly used class is these two, generally we use Uinavigationcontroller (navigation Controller, Navi) as a Uiviewcontroller (VC) container, the most common method is

//用指定的vc创建,该vc位于栈底。-(instancetype)initWithRootViewController:(UIViewController *)rootViewController; //向栈里push一个vc,位于栈顶-(void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated;//从栈里pop一个vc。-(nullable UIViewController *)popViewControllerAnimated:(BOOL)animated;

The general app only needs to use a Navi, in the appdelegate to complete the initialization, the subsequent interface migration is push and pop. It is important to note that after using Navi, each interface produces a navigationbar, which is the navigation bar at the top of the interface. The purpose of the navigation bar is to display the current interface title and return button, and to support yourself by adding the necessary accessibility features. In any VC, you can

self.navigationController.navigationBarOrself.navigationItem

To access this component, such as setting the background color, adding buttons, etc.:

[self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:19], NSForegroundColorAttributeName : someColor}];[self.navigationController.navigationBar setBackgroundColor:[UIColor whiteColor]];UIBarButtonItem  * activityDetail = [[UIBarButtonItem alloc] initWithTitle:@“帮助” style:UIBarButtonItemStylePlain target:self action:@selector(helpButtonClicked)];self.navigationItem.rightBarButtonItem = activityDetail;
Uiviewcontroller

As the base class of the view controller, we usually add the view code inside, display the logic, including the button event, proxy method (such as TableView agent, etc.). If you do not pay attention to the VC will become very large, if the number of rows is not easy to maintain, so that complex pages should be architectural distinction, such as the MVVM pattern will view,viewmodel out. It's not a fine place to talk.
The most important methods of VC include:

Life cycle-related methods

//重写该方法意味着不加载外部的xib文件,自己绘制界面-(void)loadView; -(void)viewDidLoad; -(void)viewWillAppear:(BOOL)animated;   -(void)viewDidAppear:(BOOL)animated;

The above method is called sequentially during the view load process. It is common to add custom view in Loadview or viewdidload, but you cannot add overly time-consuming operations to avoid the lag caused by blocked interface loading. In general, such as network operations, database operations loaded Viewdidappear, interface loading is visible after execution.

UIView and important sub-categories

UIView

Summarize the common methods and properties of UIView, and then describe the experience of using common view controls.
Initialize the method with a frame as the argument.

    • (instancetype) initWithFrame: (CGRect) frame

Basic

    • Userinteractionenabled
      The default yes, indicates whether there is user operability, and no gesture will take effect when set to No. When the view overlaps, the user's touch reaches the first view that opens the Userinteractionenabled=yes. This feature is used in two ways: through and interception, which can make transparent non-interactive backgrounds, which can be used for example in loading this mask.
    • Layer
      UIView internal implementation, the type is Calayer, and encapsulates a lot of content that is not exposed to uiview, such as the Cornerradius attribute implementation fillet can only call View.layer.cornerRadius.
    • Tag
      Used in conjunction with Viewwithtag, similar to the Findviewbyid in Android, similar to the use of getElementById in JavaScript. But instead of using it globally, find the target tag in a view's child view. A typical scenario, such as two controls, binds a VC as a delegate, and the implemented protocol can be used to determine which control's event is from the tag.

Location related to space:

    • Frame
    • Bounds

Each uiview has frame and bounds two properties that represent the rectangle relative to the parent container and the rectangle relative to the container (a bit difficult to understand)

struct CGRect {   CGPoint origin;   CGSize size; };

Bound is generally used to modify the relative position of the view, similar to the relative layout in CSS, and frame is similar to absolute layout.


Paste_image.png
    • Center
      Center Point Cgpoint
    • Transform
      The affine transformation of a view, which is cgaffinetransformidentity by default, is interpreted as the original transformation, meaning that it is maintained as is. By modifying this value, you can change the appearance of the view, especially when used in animations.
    • Contentscalefactor
      Scale CGFloat
    • -sizethatfits:
      Method that returns the size that is appropriate for the subclass.

Level of view

    • Subviews
      Return all sub-views
    • Superview
      Return to Parent View
    • Window
      Returns the Window object of the view
    • -(void) Removefromsuperview;
      Delete yourself from the parent view
    • -(void) Addsubview: (UIView *) view;
      Add Child view
    • -(void) Bringsubviewtofront: (UIView *) view;
      The handle view pulls to the front (in case of overlap, the default is to cover the previous view in the order of addition)
    • -(void) Sendsubviewtoback: (UIView *) view;
      Put the view to the end
    • -(void) layoutsubviews;
      Override Point. Called by layoutifneeded automatically. As of IOS 6.0, when constraints-based layout is used. The timing of this method's invocation:
      Addsubview will trigger layoutsubviews.
      Setting the frame of the view will trigger Layoutsubviews, of course, if the frame value has changed before and after the setting
      Scrolling a uiscrollview will trigger layoutsubviews
      Rotating screen triggers the Layoutsubviews event on the parent UIView-the Layoutsubviews event on the parent UIView is also triggered when a uiview size is changed

Drawing of view

    • (void) DrawRect: (cgrect) rect;
      Triggered by Setneedsdisplay, you can override this method to implement a custom view, such as executing inside a
- (void)drawRect:(CGRect)rect {      // Drawing code.      //获得处理的上下文        CGContextRef context = UIGraphicsGetCurrentContext();        //设置线条样式        CGContextSetLineCap(context, kCGLineCapSquare);         //设置线条粗细宽度        CGContextSetLineWidth(context, 1.0);         //设置颜色        CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0);         //开始一个起始路径        CGContextBeginPath(context);         //起始点设置为(0,0):注意这是上下文对应区域中的相对坐标,        CGContextMoveToPoint(context, 0, 0);         //设置下一个坐标点        CGContextAddLineToPoint(context, 100, 100);         //设置下一个坐标点        CGContextAddLineToPoint(context, 0, 150);        //设置下一个坐标点        CGContextAddLineToPoint(context, 50, 180);        //连接上面定义的坐标点        CGContextStrokePath(context);   }

Call timing DrawRect is dropped after the Controller.loadview,viewdidload two method. So don't worry. In the controller, these view drawrect begin to draw. This allows you to set some values in the controller to the view ( If you need to use some variable values for these view draw).

    • Clipstobounds
      The default no, which represents a child element that can be displayed beyond the bounds of the view.
    • BackgroundColor
      Background color
    • Alpha
      Transparency, the default is 1.0 for opacity, and note that when alpha is 0 o'clock equivalent to hidden, the control cannot receive a click event. Note that this value affects the drawing of the child view, but the alpha of the child view is not affected, and the alpha actual effect when the child view is drawn equals the product of all the alpha on the containing chain.
    • Opaque
      Opaque, default is yes
    • Hidden
      Hidden, default to No
    • Contentmode
      Reference Uiviewcontentmode, there are multiple display modes,

Paste_image.png

Animation related

- +(void)animateWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewAnimationOptions)options animations:(void (^ )(void))animations completion:(void (^ __nullable)(BOOL finished))completion

The method accepts several parameters: duration, delay, options, animations, completion. The duration represents how long the delay represents how long it will take to start execution, option reference uiviewanimationoptions (too large here), animation and completion are a block, Represents the execution of the animation and code that executes after completion. A sample code (the effect of a quick zoom out after zooming in):


Paste_image.png


Other methods are similar to this method and are actually used in accordance with the actual situation.

Gesture-related
Add and remove gestures, but more.

    • -(void) Addgesturerecognizer: (uigesturerecognizer*) Gesturerecognizer;
    • -(void) Removegesturerecognizer: (uigesturerecognizer*) Gesturerecognizer;
Uicontrol

Subclasses include:


Paste_image.png


Among them, UIButton and uitextfield,uiswitch are usually very common controls, as their base class is necessary to introduce.

Important Properties and methods:

    • Enabled
      is active, default Yes, set to No is visually grayed out
    • Selected
      Checked, default no, reference uicontrolstate
    • Highlighted
      Whether highlighted, default no, reference uicontrolstate
    • State
      Uicontrolstate type

Uicontrol Basic state change process is as follows
1. When nothing is done: Normal
2. When your finger is pressed down, not yet in place: highlighted
3. When the finger is released: If the Uicontrol has Selected status, it will become: Selected
Repeat the above procedure once and then from Selected->highlighted-> Normal
But ordinary UIButton this uicontrol subclass, there is no Selected state, it is only normal and highlighted, will only switch between the two states. (Under normal circumstances, if you set the disable, it will change to Disabled)

Button Events

- (void)addTarget:(nullable id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;

Normal buttons Bind events by this method, where Sel is a method pointer, and uicontrolevents defines several types of events that can be sent. button click General Use UIControlEventTouchUpInside. The delegate presses down within the scope of the control and releases. The rest of the properties can refer to uicontrolevents.

Custom Event implementations

- (BOOL)beginTrackingWithTouch:(UITouch *)touch withEvent:(nullable UIEvent *)event;- (BOOL)continueTrackingWithTouch:(UITouch *)touch withEvent:(nullable UIEvent *)event;- (void)endTrackingWithTouch:(nullable UITouch *)touch withEvent:(nullable UIEvent *)event;

Through the above three methods can implement the custom control, for example, to implement the slider effect, first call begin, and then use the value of Touch.locationinview in continue to change the values of the slider, complete the network, database and other operations in end.

"View Layer" interface drawing

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.