swift和swiftui_SwiftUI提示和技巧

本文主要探讨了Swift和SwiftUI的相关知识,分享了一些实用的SwiftUI提示和技巧,帮助开发者提升SwiftUI应用的开发效率。
摘要由CSDN通过智能技术生成

swift和swiftui

SwiftUI has changed the way we build user interfaces in our iOS applications. The declarative state-driven framework is concise and easy on the eyes primarily due to function builders that power the DSL language.

SwiftUI改变了我们在iOS应用程序中构建用户界面的方式。 声明性的状态驱动框架简洁明了,这主要归功于为DSL语言提供支持的功能构建器。

With the number of features that have already been presented since its debut, keeping track of some cool tricks can become a challenge. Thankfully, this article is just the cheat sheet you need for such cases.

自首次亮相以来就已经呈现出许多功能,要跟踪一些很酷的技巧可能会成为一个挑战。 幸运的是,本文只是您遇到这种情况所需的备忘单。

In the following sections, I’ve compiled a list of tips and tricks that should help you build SwiftUI applications easily. Let’s get started.

在以下各节中,我整理了一系列提示和技巧,这些提示和技巧可以帮助您轻松构建SwiftUI应用程序。 让我们开始吧。

当您使用不同的类型时,将视图包装在AnyView或组中 (Wrap Views in AnyView or Groups When You Have Different Types)

The some keyword was introduced in Swift 5.1 for defining opaque types. It allows the compiler to decide the concrete type of the function based on the returned value.

在Swift 5.1中引入了some关键字,用于定义不透明类型。 它允许编译器根据返回的值确定函数的具体类型。

While this is all good for single-branch code or when the view types are alike, it would lead to a compiler error when you have multiple-branch code with different views.

虽然这对于单分支代码或视图类型相同都很好,但是当您拥有具有不同视图的多分支代码时,这将导致编译器错误。

Specifically, the SwiftUI interface wouldn’t be able to determine a single opaque type. We can work around this by wrapping the set of views in a Group or AnyView.

具体来说,SwiftUI界面将无法确定单个不透明类型。 我们可以通过将视图集包装在GroupAnyView来解决此问题。

AnyView ensures that there’s a single opaque return type, but make sure you don’t use this too often.

AnyView确保只有一个不透明的返回类型,但是请确保您不要经常使用此类型。

Image for post

The tip above is useful when using switch statements in the SwiftUI body as well. However, a better alternative in such scenarios would be to extract the switch statement in a separate function.

当在SwiftUI主体中使用switch语句时,上面的技巧也很有用。 但是,在这种情况下,更好的选择是在单独的函数中提取switch语句。

通过解耦独立的视图来防止状态变化时整个SwiftUI主体的重新加载 (Prevent the Reload of Whole SwiftUI Body on State Changes by Decoupling Independent Views)

Being a state-driven framework, whenever a sta

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值