简体   繁体   English

在没有情节提要Swift 4的情况下构建UI元素

[英]Building UI Elements without the storyboard Swift 4

I have just recently decided to transition from building UI elements using the storyboard to building them programmatically. 我最近决定从使用情节提要构建UI元素过渡到以编程方式构建它们。

While looking up tutorials online, I saw some people liked to create their UIs using closures. 在网上查找教程时,我看到有些人喜欢使用闭包创建UI。

For example: let label: UILabel = { // they would customize their UI elements between the brackets } 例如: let label: UILabel = { // they would customize their UI elements between the brackets }

I was wondering if this was some sort of conventional way used to build UI Elements ? 我想知道这是否是用于构建UI元素的某种常规方式?

So far I've been sticking up with declaring my variables(including UI elements declaration) before the viewDidLoad method and declaring functions to configure them below it before calling them in the same 'viewDidLoad' method. 到目前为止,我一直坚持在viewDidLoad方法之前声明变量(包括UI元素声明),并在使用相同的“ viewDidLoad”方法调用它们之前声明在其下方配置它们的函数。

Is it wrong to do it this way? 这样做是错误的吗?

There is nothing wrong in the way which you do, but using closures, is a common practice in iOS programming. 您的操作方式没有错,但是使用闭包是iOS编程中的常见做法。 Closures have multiple benefits such as all the view related configuration code is placed in a single place, the code is readable, and it becomes straightforward to make changes to the code and debug if there are any bugs present. 闭包有很多好处,例如所有与视图相关的配置代码都放在一个地方,代码易于阅读,并且可以轻松更改代码并调试是否存在任何错误。

It's about preference. 这与偏好有关。 But, in the way you described with closures, you won't be able to access other properties even if you declare them before the property inside which you need them. 但是,按照用闭包描述的方式,即使在需要它们的属性之前声明其他属性,也将无法访问它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM