swift 我怎么用斯威夫特做一个新的系列

tsm1rwdh  于 2023-04-19  发布在  Swift
关注(0)|答案(6)|浏览(74)

有没有一种方法可以在swift中创建一个新的行,比如java的“\n”?

var example: String = "Hello World \n This is a new line"
ldxq2e6h

ldxq2e6h1#

你应该可以在Swift字符串中使用\n,它应该像预期的那样工作,创建一个换行符。你需要删除\n后面的空格,以进行正确的格式设置,如下所示:

var example: String = "Hello World \nThis is a new line"

如果打印到控制台,则应变为:

Hello World
This is a new line

但是,根据您将如何使用此字符串,还有一些其他注意事项,例如:

  • 如果要将其设置为UILabel的text属性,请确保UILabel的numberOfLines = 0,这允许无限行。
  • 在某些网络用例中,请使用\r\n,即Windows换行符。
    编辑:您说使用的是UITextField,但不支持多行,必须使用UITextView。
f2uvfpb9

f2uvfpb92#

也很有用:

let multiLineString = """
                  Line One
                  Line Two
                  Line Three
                  """
  • 使代码读起来更容易理解
  • 允许复制粘贴
ig9co6j1

ig9co6j13#

你可以使用下面的代码:

var example: String = "Hello World \r\n This is a new line"
tyg4sfes

tyg4sfes4#

你能做到的

textView.text = "Name: \(string1) \n" + "Phone Number: \(string2)"

输出将为
Name:output of string1电话号码:string2的输出

toiithl6

toiithl65#

"\n"并不是到处都能用!

例如,在电子邮件中,如果您在自定义键盘中使用它,它会将确切的“\n”添加到文本中,而不是新的一行:textDocumentProxy.insertText("\n")
还有另外一个新行字符可用,但我不能简单地将它们粘贴在这里(因为它们构成了新行)。
使用此扩展:

extension CharacterSet {
    var allCharacters: [Character] {
        var result: [Character] = []
        for plane: UInt8 in 0...16 where self.hasMember(inPlane: plane) {
            for unicode in UInt32(plane) << 16 ..< UInt32(plane + 1) << 16 {
                if let uniChar = UnicodeScalar(unicode), self.contains(uniChar) {
                    result.append(Character(uniChar))
                }
            }
        }
        return result
    }
}

您可以访问任何CharacterSet中的所有字符。有一个名为newlines的字符集。使用其中一个来满足您的要求:

let newlines = CharacterSet.newlines.allCharacters
for newLine in newlines {
    print("Hello World \(newLine) This is a new line")
}

然后把你测试过的字符集保存起来,并在任何地方使用它。注意,你不能依赖字符集的索引,它可能会改变。

但大多数时候"\n"只是按预期工作。

0yg35tkg

0yg35tkg6#

我已经尝试过这种方式,所以更容易阅读和方便复制和粘贴:

let exampleString = """
              Begin of string
              Line 1
              Line 2
              End of string
              """

相关问题