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

时间:2015-01-21 19:15:31

标签: string swift word-wrap

从字符串中在Swift中创建自动换行的最简单方法是什么?让我们说我有一个150个字符的字符串,我希望每50个字符开一个新行。非常感谢你的想法。

2 个答案:

答案 0 :(得分:1)

这样的事情怎么样:

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 a\nstring\nthat\nwraps!")
}

func testWrapLongWords() {
    let value = "Thesewordsare toolongforasingle line".wrap(10)
    XCTAssertEqual(value, "Thesewordsare\ntoolongforasingle\nline")
}

答案 1 :(得分:-1)

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

 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.
}


}