我在swift 3和Xcode 8中编写代码。
代码如下:
import Foundation
import UIKit
class CashTextFieldDelegate : NSObject, UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let oldText = textField.text! as NSString
var newText = oldText.replacingCharacters(in: range, with: string) as NSString
var newTextString = String(newText)
let digits = NSCharacterSet.decimalDigits
var digitText = ""
for c in newTextString.unicodeScalars {
if digits.contains(c) {
digitText.append(String(c))
}
}
// Format the new string
if let numOfPennies = Int(digitText) {
newText = "$" + self.dollarStringFromInt(numOfPennies)+ "." + self.centsStringFromInt(numOfPennies)
} else {
newText = "$0.00"
}
textField.text = newText as String
return false
}
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField.text!.isEmpty {
textField.text = "$0.00"
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true;
}
func dollarStringFromInt(value: Int) -> String {
return String(value / 100)
}
func centsStringFromInt(value: Int) -> String {
let cents = value % 100
var centsString = String(cents)
if cents < 10 {
centsString = "0" + centsString
}
return centsString
}
}
表示上面这行代码:
newText = "$" + self.dollarStringFromInt(numOfPennies) + "." + self.centsStringFromInt(numOfPennies)
我得到这样的错误:
No '+' candidates produce the expected contextual result type 'NSString'.
无法解决此错误。
如果有任何帮助,只要稍加解释,我将不胜感激
与Swift 2不同,NSString
和String
之间不会自动转换。
试试这样写:
newText = ("$" + self.dollarStringFromInt(numOfPennies) + "." + self.centsStringFromInt(numOfPennies)) as NSString
你可以通过使用一致的类型——String
或NSString
来进一步清理它(例如改变函数返回值等)。