High energy warning: this article is a mixed bag, see resources at the end of the article for excerpts and citations. In addition, added some of their own views!

UI construction and debugging take up so much of our daily development time that mobile development is often referred to as interface. Improving UI layout techniques can improve development efficiency and allow more time to be spent on optimization and logic, rather than being tied to the interface business.

UI layout technology overview

  • Nib: NiB is short for NeXT Interface Builder. Nib stores interface information in binary form. It is a file format prior to IB3.0.

  • Xib: XiB is the abbreviation of XML Interface Builder, which is a new generation launched by Apple after IB3.0. It stores interface information in XML format. Xib files are compiled into NIB files before execution. (Please pay attention to the comments of Great God @protograph)

  • Storyboards are apple’s latest technology to replace XIBs in interface development. Essentially a centralized management area of XML files that can describe not only the structure of a XIB’s individual interfaces, but also the jumps and dependencies between interfaces. It’s mostly hand-pulled. It feels like a brick toy.

  • Frame: Equivalent to code storyboard, but more flexible. It is commonly used at present. Without a good fit, it can be tricky to have multiple sizes. (Welcome to add the most elegant adaptation program tutorial address)

  • AutoLayout: Automatic layout (AutoLayout) is the interface layout technology released by iOS6. The main idea of the algorithm is: the layout rules based on constraint system (essentially, linear equations that represent the layout relations of the view) are transformed into view geometric parameters that represent the rules. In fact, AutoLayout algorithm itself was not invented by 🍎, but apple implemented the algorithm in Objective-C to facilitate the use of iOS developers. AutoLayout can be used in many ways, such as (1) visual tool: Interface Builder for Xcode, (2) pure code: navigation. See Auto Layout for more information.

  • FlexBox: Flexible Box layout. Yes, it is the most popular layout on the Web (formerly the box model), and now it can be used on the APP. This solution expands many technologies, such as Yoga (the most awesome representative, produced by Facebook, derived from many upper solutions, such as cross-platform ReactNative, Android Litho, iOS Yogakit), FlexboxLayout (Android representative, Google), FlexLib, FLEX, etc. (Welcome to add)

  • SwiftUI: Official website, recommended by Apple. Read more on Apple’s new SwiftUI framework: Coding once, Universal across all five terminals

nib

Some arguments about building interfaces in iOS development

xib

Some arguments about building interfaces in iOS development

storyboard

Some arguments about building interfaces in iOS development

frame

Through the frame programming interface, the main difficulty lies in the model adaptation, but also more complicated. Here are 2 keys to fit:

Non-bangs

It is obvious that the three screens have the same aspect ratio. In addition, the screen size is 4.7+, so iPhone 6(S) is often used as a benchmark for equal scale scaling. In practice it may be all, or part of the entire page, or only wide (or high, and then adaptive on the other side).

// @property in appdelegate.hfloat autoSizeScaleX;
@property floatautoSizeScaleY; / / the AppDelegate. M#define ScreenHeight [[UIScreen mainScreen] bounds].size.height
#define ScreenWidth [[UIScreen mainScreen] bounds].size.width
 
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
   
    if(ScreenHeight > 667) {/ / here will be subject to (6) the iPhone myDelegate autoSizeScaleX = ScreenWidth / 375; myDelegate.autoSizeScaleY = ScreenHeight/667; }else {
        myDelegate.autoSizeScaleX = 1.0;
        myDelegate.autoSizeScaleY = 1.0;
    }
}
Copy the code

The height of the iPhone 6 screen is 667, so when the screen size is larger than the iPhone 6, autoSizeScaleX and autoSizeScaleY are the aspect ratio of the current screen to the iPhone 6 size. If the phone is Iphone6 then the screen ratio is 1, if it is Iphone6s, the screen ratio is enlarged, Iphone5 screen ratio is smaller. Now that we have the proportions, let’s take a look at how to solve the problem of adaptation in the code setup interface.

CGRectMake(CGFloat x, CGFloat Y, CGFloat Width, CGFloat height) this method makes our usual method to set the size in the.m file

CG_INLINE CGRect TS_CGRectMake(CGFloat x, CGFloat y, CGFloat width, CGFloat height)
{
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    CGRect rect;
    rect.origin.x = x * myDelegate.autoSizeScaleX; 
    rect.origin.y = y * myDelegate.autoSizeScaleY;
    rect.size.width = width * myDelegate.autoSizeScaleX;
    rect.size.height = height * myDelegate.autoSizeScaleY;
    return rect;
}
Copy the code

UIImageView * ImageView = [[UIImageView alloc] initWithFrame:TS_CGRectMake(100, 100, 50, 50)]; So now we have our transformed coordinates. The imageView has the same position and size ratio on the 5, 6, and 6 Plus.

It’s not just about size, it’s about text size.

#define MainScreenWidth [[UIScreen mainScreen] bounds].size.width

# define the font (R) (R) * (MainScreenWidth) / 375.0
Copy the code

So you’ll often see the following code:

self.btnForgetPassWord = [UIButton alloc]initWithFrame:TS_CGRectMake(161, 499, 54, 12);
[self.btnForgetPassWord setFont:[UIFont systemFontOfSize:font(12)]];
Copy the code

Anyway, mom doesn’t have to worry about screen adaptation anymore.

Bang models

The difference between bangs and non-bangs is that there is a SafeArea, so the simplest way is to change the size of the security area, and then adapt according to the non-bangs model.

The common solution is macros!

#define K_iPhoneXStyle ( (CGSizeEqualToSize(CGSizeMake(414, 896), [[UIScreen mainScreen] bounds].size)) || ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) : NO) )/ / or#define K_iPhoneXStyle ((KScreenWidth == 375.f && KScreenHeight == 812.f ? YES : NO) || (KScreenWidth == 414.f && KScreenHeight == 896.f ? YES : NO))/ / other macros#define KScreenWidth ([UIScreen mainScreen].bounds.size.width)
#define KScreenHeight ([UIScreen mainScreen].bounds.size.height)
#define K_iPhoneXStyle ((KScreenWidth == 375.f && KScreenHeight == 812.f ? YES : NO) || (KScreenWidth == 414.f && KScreenHeight == 896.f ? YES : NO))
#define KStatusBarAndNavigationBarHeight (K_iPhoneXStyle ? 88.f : 64.f)
#define KStatusBarHeight (K_iPhoneXStyle ? 44.f : 20.f)
#define KTabbarHeight (K_iPhoneXStyle ? 83.f : 49.f)
#define KMagrinBottom (K_iPhoneXStyle ? 34.f : 0.f)

#define KScaleWidth(width) ((width)*(KScreenWidth/375.f))
#define IsIphone6P SCREEN_WIDTH==414
#define SizeScale (IsIphone6P ? 1.5:1)
#define kFontSize(value) value*SizeScale
#define kFont(value) [UIFont systemFontOfSize:value*SizeScale]
Copy the code

Consider only most of the cases, other things such as landscape, new resolution, etc.

AutoLayout

Compared with frame, the flexibility is improved, reducing the size effect from the whole to the local, but there is still some trouble in using the update, and the new concept of priority is introduced. There are a few differences in updating methods:

  • SetNeedsLayout: Tells the page that it needs to be updated, but does not start updating immediately. LayoutSubviews is called immediately after execution.
  • LayoutIfNeeded: Notifies the page layout to be updated immediately. So it’s usually used with setNeedsLayout. You need to call this method if you want to generate a new frame immediately, so you can use this method to animate a general layout animation after updating the layout.
  • LayoutSubviews: System rewrite layout.
  • SetNeedsUpdateConstraints: told to update, but won’t immediately start.
  • Update constraint updateConstraintsIfNeeded: let us know immediately.
  • UpdateConstraints: system updateConstraints.

For more information about the use of navigation, please refer to the navigation guide.

AutoLayout’s biggest problem is that it needs to know exactly the constraints of each UI element. When page constraints are complex, it can be a great test for the programmer’s care and patience. However, this is not the most serious problem that pages are usually composed of several components assembled, is the most terrible AutoLayout does not support hot plug components, namely, no other components can destroy a depends on the component constraint component, the programmer if you want to “delete” a component, you need to add a reference point to this component’s width and height, When you need to delete, set the variable to 0, and you think you’re done? What if the component is “inserted” back in place?

FlexBox solves this problem perfectly, so keep reading.

I transferred to iOS in 2015. I learned to use the code layout of navigation directly, skipping xiB and storyboard, so I still can’t learn Interface Builder. I would like to interpret the navigation as boring. I would not experience what I see is what I receive, and THE UI code in a VC or View takes up a large part. But the experience of collaborating with other colleagues, flexibility, control, abstraction reuse, etc. is great after the beginning!

FlexBox

Finally it’s time for today’s hero! Happy ~~ have a little Web foundation can go to Flexbox layout detailed study and practice.

What does Flexbox solve?

  • Orientation (traditional layout orientation is left to right, top to bottom)
  • Elastic scaling (traditional size definition is precisely defined by pixels, etc.)
  • Element alignment (insertion and unplugging can be done)

From the above points, it seems to be a perfect solution to the slow development of iOS native layout, but it can increase the nesting hierarchy of pages and trade space for efficiency at a time when hardware performance is saturated.

I’m sure you have doubts about its efficiency! ? (AutoLayout has been updated in the comments of @Protograph, so please search for the latest information about it at 😄)

Here, according to the test code from AutoLayout layout algorithm and performance, the layout of Frame/AutoLayout/FlexBox is carried out, and the layout time of 10 ~ 350 UIViews is measured in sections. The average of 100 times layout time is taken as the result, and the time spent is in seconds. The result is shown below :(test the layout of the project code GitHub address)

Although the test results may be biased, it is clear from the line chart that the FlexBox layout performance is close to that of Frame. The 60FPS is the gold standard for iOS fluency, requiring layouts to be completed in 0.0166667 seconds, and AutoLayout can start to have problems staying smooth beyond 50 views. Xcode9.2, iPad Pro (12.9-inch)(2nd Generation) simulator.

Yoga

Yoga was originally created as an open source CSS layout library by Facebook in 2014, and was changed to Yoga in 2016. It is implemented in C, a cross-platform view-writing code based on Flexbox that makes layout easier, and supports multiple platforms including Java, C#, C, Objective-C, and Swift.

Yoga Layout’s official website. Library developers can integrate Yoga into their layout systems, just as Facebook has integrated it into its two open source projects: React Native, Litho, and Componentkit. In addition, iOS developers can directly use YogaKit to lay out the frame of the view.

React Native

RN will not go into details. Many apps are in use in the market at present, which should be the best choice for cross-platform APP development:

  • Jingdong 618: Practice of ReactNative Framework in JINGdong Wireless Terminal: This article kind of introduced me to RN, and then promoted RN in West China at the beginning of 2018, which also referred to this article. However, JD.com is now promoting Taro.
  • Meituan: only the official RN articles of Meituan were found, which are not representative. However, I believe that you should download the react-native version of meituan.com.
  • Ctrip: Ctrip should be the manufacturer that uses RN the most in APP. When it was around 0.48, ctrip deeply customized RN, such as hot update and subcontracting, etc. Many articles of Ctrip RN can be found online, such as Ctrip’s React Native clean architecture practice. Finally, CRN was opened source in 2019. Personally, I think it was too late to make much impact on the RN market.
  • Doctor: my first RN product, except IM and related pages, all pages are RN, accounting for an estimated 85%+.

Litho

Litho is a declarative framework for building efficient user interfaces (UI) on Android. It allows you to write highly-optimized Android views through a simple functional API based on Java annotations. It was primarily built to implement complex scrollable UIs based on RecyclerView. With Litho, you build your UI in terms of components instead of interacting directly with traditional Android views. A component is essentially a function that takes immutable inputs, called props, and returns a component hierarchy describing your user interface.

Litho is a declarative framework for efficiently building Android UIs and creating high quality Android views through annotations API, which is ideal for complex scrolling lists based on Recyclerview. Litho uses a series of components to build views instead of Android’s traditional view interaction. A component is essentially a function that takes immutable input named Props and returns a component hierarchy that describes the user interface.

Litho is a completely different UI framework from the traditional Android. It inherits the bold and innovative style of Facebook and makes a breakthrough in implementing the React style UI framework on Android. The architecture diagram is as follows:

The use of the basic skills | Litho and principle analysis

YogaKit

IOS Yoga end UI library Componentkit, but I feel very difficult to use after reading the document, so skip.

But YogaKit is good, and supports OC and Swift, Yoga tutorials – This Swift based YogaKit tutorial is good using a cross-platform layout engine.

Ps: I would like to find a replacement for navigation. I would like to support Flex layout, so I hope to learn about YogaKit, but I am disappointed 😞. First, the code is cumbersome, and second, YogaKit is not widely used. I’m going to study RN

FlexboxLayout

FlexboxLayout is a Google product that only supports Android, so I look forward to your comments on this framework.

By the way, Google looks at what languages and technologies are hot, jumps in and develops one on its own. Golang, Angular, Android Studio, Dart, Flutter, etc., plus the Google plot of domestic tech developers, so you can see for yourself… Except for the JS engine – V8

swiftUI

UI on iOS, I think swiftUI is the future king! I don’t take arguments, hahahahahahahaha… IOS UI development language is Objective-C and Swift, from compiled OC to interpreted SWIFT. From the perspective of language, the span is still quite large. In the modern era of rapid development of many technologies, interpreted language is more suitable for the future, but Swift has not played any two points on cross-platform. Not even on the iPhone or MAC.

Without swift’s entry – to – entry event, the Swift market might be a different story! Hope swift 5 stabilizes.

After the language

The basic layout of UI is the same, from Graphics drawing OpenGL, to UI Library, to UI Controls, and then to APP. The computer development has not changed until now, such as MFC on Windows, UIKit on iOS, and the newly released Flutter, etc.

This is based on TCP/IP’s seven-tier model (I think it’s the best architecture in the world, no one else, no one else!). Only after stratification, different personnel can play different roles to complete the corresponding work. We say UI is the software level, is running on the hardware, so software to hardware connection to rely on graphics drawing, this work is completed by the operating system.

With the operating system this environment, in order to establish an ecosystem, it is necessary to provide external response to the development kit, such as UI library, network library, driver library, etc., which is particularly obvious in Windows cash withdrawal. Then developers will join your development camp, and then your market will gradually expand. Therefore, why do you often hear that a language and technology also need strong companies and financial support, such as Microsoft, Google, Amazon, Facebook, SDK of many third-party manufacturers and so on? Please note that vendors such as Ali Cloud SDK and Tencent SDK are also at this level. You can regard Windows, Android, iOS and other operating systems as tier 1 manufacturers, and Facebook, Ali Cloud, Tencent cloud and other service providers as tier 2 manufacturers.

With libraries and Control provided by all levels of manufacturers, it is better to create apps that blossom, and software developers like us emerge from different directions. So when you look at a new UI library or technology, you need to analyze its rationale and application to find the right position. If you don’t analyze the technology behind it, you won’t get the most out of it.

Like React Native, you ask me to do IM and multimedia, I’ll slap you in the face! RN just lowers the threshold of APP UI and expands its audience, just like the slogan of React “Learn once write anywhere”. The idea behind RN is to dynamically control native UI layouts through JavaScript and JavaScript interpreters, in much the same way that native UI layouts were automatically generated by parsing XML, and that JavaScript syntactic scripts like Lua have become popular in the game industry. That’s how HOT updates work in RN — updating JavaScript files to update UI layouts and business logic, etc., so the core of RN is a hot update with ES 6/7/8/… JavaScript and the corresponding JavaScript interpreter, for JavaScript interpreters in RN, look at the reverse Futter? Facebook launches new cross-platform engine Hermes! JS engine big PK: JSC vs V8 vs Hermes

Not limited to RN, but if you want to do better and better, you need to do more research. Just because you know how to React, don’t think you can build an APP. A library dependency problem will kill you. Not your long beauty, you can want to be beautiful! Like if you were to draw a control using openGL’s API, and you couldn’t draw it well, and then openGL didn’t work, right? ! Now I can only send you a word, go!

Having said that, I don’t want any one UI library to be awesome, but I hope FlexBox, the UI specification, can expand its influence on the APP side, try to keep in line with the better layout of the Web side, and finally achieve unification, the most fundamental cross-platform, but there are many libraries or solutions to achieve it.





The MyLinearLayout mentioned by the Flutter is also excellent and powerful, compatible with old and new layouts. Technical officers can try it, maybe you also like it. But I feel that poor documentation, especially in terms of usage, can make it harder to get started.

The following comments @prehistoric Tuten mentioned the history of iOS layout, this article mentioned some wrong, please pay attention to screen! (I want to modify, but I don’t know how to modify 😔).

Resources :(in no particular order)

  • Auto Layout
  • FlexBox layout and yogaKit framework on iOS
  • Discuss performance from Auto Layout Layout algorithm
  • How to use YogaKit for iOS
  • Flexbox layout details
  • IOS Screen adaptation (pure code)
  • A few lines of code to make ios screen adaptation easy
  • IOS screen adaptation solutions and UI adaptation solutions in different sizes
  • I’ll take pictures next
  • Jingdong 618: ReactNative Framework in jingdong wireless Terminal practice
  • React Native Clean architecture practice
  • The use of the basic skills | Litho and principle analysis