gpt4 book ai didi

ios - Swift 中的 String.enumerateSubstringsInRange 停止

转载 作者:可可西里 更新时间:2023-11-01 01:39:15 32 4
gpt4 key购买 nike

首先,感谢 Stonz2 在 Find last visible line index in NSAttributedString's drawWithRect 中的回答

我有类似的麻烦,所以我得到了这个 objective-c 函数。

但我正在使用 swift,当我想将其转换为 swift 时,我遇到了麻烦。

这是我刚刚转换的 Stonz2 答案的快速版本。

func removeLastWord( str:String ) -> String{
var range = Range(start:count(str), end:0)
let opts:NSStringEnumerationOptions = .ByWords | .Reverse | .SubstringNotRequired

// trouble in here, Cannot invoke 'enumerateSubstringsInRange' with an argument list of type '(Range<Int>, options: NSStringEnumerationOptions, (_, _, _, _) -> ())'
str.enumerateSubstringsInRange(Range(start:0, end:count(str)), options: opts) {
(substring, substringRange, enclosingRange, stop) -> () in
range = substringRange
stops = true
}

return str.substringToIndex(advance(str.startIndex, range.endIndex))
}

func pageSplitIndexForString( string:String, frame:CGRect, font:UIFont ) -> Int {

let fixedWidth = frame.size.width
let textView = UITextView()

textView.text = string
textView.font = font

var newSize = CGSizeMake(fixedWidth, CGFloat.max)
textView.frame.size = newSize
textView.sizeToFit()
var newFrame = textView.frame

println(textView.frame)

while ( newFrame.height > frame.height ) {
textView.text = removeLastWord(textView.text)
newSize = CGSizeMake(fixedWidth, CGFloat.max)
textView.frame.size = newSize
textView.sizeToFit()
// fmaxf fmax?
newFrame.size = CGSizeMake(fmax(newSize.width, fixedWidth), newSize.height)
}

var str = string.substringFromIndex(advance(textView.text.startIndex, count(textView.text)))

println("Page one text: \(textView.text)")
println("Page two text: \(str)")

return (textView.text as NSString).length
}

所以我想知道在 swift 中转换这个 objective-c 函数的正确方法是什么?

最佳答案

你可以使用这个删除最后一个词,

func removeLastWord( str:String ) -> String {

var start = str.startIndex // Start at the string's start index
var end = str.endIndex
var range: Range<String.Index> = Range<String.Index>(start: start,end: end)

let opts:NSStringEnumerationOptions = .ByWords | .Reverse

str.enumerateSubstringsInRange(range, options: opts) {

(substring, substringRange, enclosingRange, stop) -> () in

range = substringRange
stop = true
}

return str.substringToIndex(range.startIndex)
}

关于ios - Swift 中的 String.enumerateSubstringsInRange 停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31983533/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com