我是swift的新手,但是从ObjectiveC背景来看,我尝试通过单击按钮将文本字段输入到var中。
现在,当我尝试使用" stringByTrimmingCharactersInSet"删除空格时还有很多其他的选择,它不起作用。这是我的代码,
var someVariable = urlInputComponent.text!
if someVariable.containsString(" "){
someVariable = someVariable.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
print(someVariable)
}
我还尝试将结果分配给新的var,
let trimmed: String = someVariable.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
print(trimmed)
但仍然无法移除空白。我的猜测是我对" Unwrapped value"概念,如果有人可以帮助我,它会非常有用。谢谢!
答案 0 :(得分:6)
尝试替代方式
urlInputComponent.text! = urlInputComponent.text!.stringByReplacingOccurrencesOfString(" ", withString: "")
或者试试这个
let trimmed = "".join(urlInputComponent.text!.characters.map({ $0 == " " ? "" : String($0) }))
print (trimmed)
答案 1 :(得分:2)
这是您可以用来开始清洁的代码:
extension String {
func condenseWhitespace() -> String {
let components = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).filter({!Swift.isEmpty($0)})
return " ".join(components)
}
}
var string = " Lorem \r ipsum dolar sit amet. "
println(string.condenseWhitespace())
将此委托方法添加到您的代码中:
func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {
if range.location == 0 && string == " " {
return false
}
return true
}
答案 2 :(得分:2)
对于 Swift 3 ,您可以使用:
//let myTextField.text = " Hello World"
myTextField.text.replacingOccurrences(of: " ", with: "")
// Result: "Helloworld"
答案 3 :(得分:0)
<div id="portfolio-items"></div>