我试图使用UITextView的第一行设置我的笔记的标题。只有我的代码的最后一部分不起作用。
(如果您想知道为什么我使用"否则"除了30个字符的声明之外,因为如果我不放入注意至少30个字符,这是一个错误)
override func viewWillDisappear(animated: Bool) {
detailItem!.noteText = self.textView.text
if !self.textView.text.isEmpty {
var textViewString:String = self.textView.text
if let range = self.textView.text.rangeOfString("\n") {
let rangeOfString = self.textView.text.startIndex ..< range.endIndex
let firstLine = self.textView.text.substringWithRange(rangeOfString)
detailItem?.noteTitle = firstLine
} else {
// take up to the first 30 characters as the title
let length = count(self.textView.text)
if length > 30 {
let firstLine = (textView.text as NSString).substringFromIndex(30)
detailItem?.noteTitle = firstLine
} else {
let firstLine = (textView.text as NSString).substringFromIndex(length)
detailItem?.noteTitle = firstLine
}
}
}
所以不起作用的代码就是最后一部分:
} else {
let firstLine = (textView.text as NSString).substringFromIndex(length)
detailItem?.noteTitle = firstLine
}
问题:
1)普通旧int和变量是什么区别?
2)如果我的方法不可能,那么实现相同结果的工作是什么?
答案 0 :(得分:2)
使用.substringToIndex()而不是.substringFromIndex(),然后您将获得正确的结果。
答案 1 :(得分:1)
我有同样的问题,我发现这种方式非常有效。您在代码注释中有解释:
//If it's empty will return this values
if self.txtText.text.isEmpty {
title = "(Empty Note)"
texto = "(Empty Note)"
}
//If it's not...
else
{
//We provide the value "\n" to say which will be te last character
let till: Character = "\n"
if let idx = texto.characters.indexOf(till) {
//Get the position of this character
let pos = texto.startIndex.distanceTo(idx)
//Substract 1 to not add the \n to the title
firstLine = (txtText.text as NSString).substringToIndex(pos-1)
}
else {
//If it's longer than 30 chars, get 30
if texto.characters.count >= 30{
firstLine = (txtText.text as NSString).substringToIndex(30)
}
//If it's shorter, count the chars and get till the last of this line
else{
firstLine = (txtText.text as NSString).substringToIndex(texto.characters.count)
}
}
title = firstLine
}