在 swift 中从字符串创建自动换行的最简单方法



Swift 中从字符串创建自动换行的最简单方法是什么?假设我有一个包含 150 个字符的字符串,我希望每 50 个字符开始一个新行。非常感谢您的想法。

像这样的事情怎么样:

extension String {
    public func wrap(columns: Int = 80) -> String {
        let scanner = NSScanner(string: self)
        var result = ""
        var currentLineLength = 0
        var word: NSString?
        while scanner.scanUpToCharactersFromSet(NSMutableCharacterSet.whitespaceAndNewlineCharacterSet(), intoString: &word), let word = word {
            let wordLength = word.length
            if currentLineLength != 0 && currentLineLength + wordLength + 1 > columns {
                // too long for current line, wrap
                result += "n"
                currentLineLength = 0
            }
            // append the word
            if currentLineLength != 0 {
                result += " "
                currentLineLength += 1
            }
            result += word as String
            currentLineLength += wordLength
        }
        return result
    }
}

通过测试:

func testWrapSimple() {
    let value = "This is a string that wraps!".wrap(10)
    XCTAssertEqual(value, "This is anstringnthatnwraps!")
}
func testWrapLongWords() {
    let value = "Thesewordsare toolongforasingle line".wrap(10)
    XCTAssertEqual(value, "Thesewordsarentoolongforasinglenline")
}

这是一个粗略的快速自动换行程序。随意发表评论 - 因为每天都是上学日!

 import UIKit
class ViewController: UIViewController {

    var string1: String = "I think this is a good word wrap method, but I must try many times!"

    override func viewDidLoad() {

    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let arr = split(string1, { $0 == " "}, maxSplit: Int.max, allowEmptySlices: false)
    println(arr)
    for words in arr  {

        println("variable string1 has (countElements(words)) characters!")
                        }
    var firstThirtyFive: String =  string1.substringToIndex(advance(string1.startIndex, 35))
        println(firstThirtyFive)
    var arr2 = split(firstThirtyFive, { $0 == " "}, maxSplit: Int.max, allowEmptySlices: false)
     println(arr2.count)
    var removed = arr2.removeLast()
    println(arr2)
    println(removed)


    var fromThirtyFive:String = string1.substringFromIndex(advance(string1.startIndex,35))

     println(fromThirtyFive)
    var arr3 = split(fromThirtyFive, { $0 == " "}, maxSplit: Int.max, allowEmptySlices: false)
    var removeFirst = arr3.removeAtIndex(0)
    var newWord:String = removed + removeFirst

    println(removeFirst)
    println(arr3)
    println(newWord)
    arr3.insert(newWord, atIndex: 0)
    println(arr3)

    let res1 = join(" ", arr2)
    let res2 = join(" ", arr3)
    println(res1)
    println(res2)



}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

最新更新