我一直在关注Apple的SwiftUI教程。在此过程中,我经常将Text对象与以下初始化程序一起使用:
/// Creates an instance that displays `content` verbatim.
public init<S>(_ content: S) where S : StringProtocol
Run Code Online (Sandbox Code Playgroud)
Now, in the fifth tutorial of the series, I've encountered the following usage of Text:
Text(verbatim: "")
Run Code Online (Sandbox Code Playgroud)
The description in the interface is the same as for the other initializer:
Text(verbatim: "")
Run Code Online (Sandbox Code Playgroud)
What's the two initializers for and how are they different / when would I use which?
Mat*_*ini 10
Text(verbatim: ) returns text as it is - hence the verbatim argument name.
Text(:_) checks if the argument is a localized key.
If it is, it returns the corresponding localized string.
It it isn't, it will print the text verbatim.
正如在 WWDC19 介绍它的一些会议中所指出的那样,SwiftUI 默认情况下会尝试为您处理一大堆良好的平台公民行为,这些行为最终用户会考虑应用程序的基本要求,但往往会使开发人员的工作复杂化。
本地化就是其中之一——Text初始化器会自动做正确的事情。例子:
Text(“Some Text”) 将字符串文字视为本地化的,因为静态定义的文本几乎总是旨在成为 UI 文本。 Text(“\(items.count) items”),它正确本地化格式字符串并插入内插值。Text(item.name) 在运行时动态提供不同的字符串,因此文本几乎可以肯定是“内容”,无论语言环境如何(因为它来自用户,来自程序外部等)。这意味着在 99% 的情况下,您只需进行最自然、最简洁的调用来设置您的 UI,最终得到一个准备好进行本地化的应用程序,而您无需像以前那样返回并更改一堆代码与其他 UI 框架。
如果您的应用程序有一些不符合这些假设的部分,Text(verbatim:)并且Text(_:tableName:bundle:comment:)让您制作非本地化的静态文本和本地化的程序化文本。
| 归档时间: |
|
| 查看次数: |
770 次 |
| 最近记录: |