获取 UITextView 中的当前段落?
Get current paragraph in UITextView?
我想检测当前段落,这是我目前的代码,但效果不是很好。假设我有 3 个段落,当光标在它们之间时,它会选择下一个,这是不正确的。有更好的方法吗?
使用这段代码,我想检测当前段落,然后更改该段落的字体,然后继续使用该字体书写。
func textViewDidChangeSelection(textView: UITextView)
{
// print("selected")
//stylesDefaults()
var arr = [String]()
composeTextView.text.enumerateSubstringsInRange(Range(start: composeTextView.text.startIndex, end: composeTextView.text.endIndex), options: NSStringEnumerationOptions.ByParagraphs,
{ (substring, substringRange, enclosingRange, bool) -> () in arr.append(substring!)
})
if(composeTextView.text.characters.count != 0)
{
self.titleTextField.text = arr[0]
}
let currentRange : NSRange = composeTextView.selectedRange
var charCounter : Int = 0
var found : Bool = false
for (var i = 0; i < arr.count; i++)
{
charCounter = charCounter + arr[i].characters.count
if found == false
{
if(charCounter > currentRange.location)
{
print(arr[i])
found = true
}
}
}
}
听起来你需要NSString
的paragraphRangeForRange:
方法:
let composeText = composeTextView.text as NSString
let paragraphRange = composeText.paragraphRangeForRange(composeTextView.selectedRange)
print(composeText.substringWithRange(paragraphRange))
我想检测当前段落,这是我目前的代码,但效果不是很好。假设我有 3 个段落,当光标在它们之间时,它会选择下一个,这是不正确的。有更好的方法吗?
使用这段代码,我想检测当前段落,然后更改该段落的字体,然后继续使用该字体书写。
func textViewDidChangeSelection(textView: UITextView)
{
// print("selected")
//stylesDefaults()
var arr = [String]()
composeTextView.text.enumerateSubstringsInRange(Range(start: composeTextView.text.startIndex, end: composeTextView.text.endIndex), options: NSStringEnumerationOptions.ByParagraphs,
{ (substring, substringRange, enclosingRange, bool) -> () in arr.append(substring!)
})
if(composeTextView.text.characters.count != 0)
{
self.titleTextField.text = arr[0]
}
let currentRange : NSRange = composeTextView.selectedRange
var charCounter : Int = 0
var found : Bool = false
for (var i = 0; i < arr.count; i++)
{
charCounter = charCounter + arr[i].characters.count
if found == false
{
if(charCounter > currentRange.location)
{
print(arr[i])
found = true
}
}
}
}
听起来你需要NSString
的paragraphRangeForRange:
方法:
let composeText = composeTextView.text as NSString
let paragraphRange = composeText.paragraphRangeForRange(composeTextView.selectedRange)
print(composeText.substringWithRange(paragraphRange))