gpt4 book ai didi

objective-c - 在 UITextFieldDelegate 函数中使用自定义 UITextField

转载 作者:行者123 更新时间:2023-11-30 13:22:41 25 4
gpt4 key购买 nike

我正在尝试在 Swift 中创建自定义 UI 文本字段。这是我的代码

public class AmountTextField : UITextField{

let currencyFormattor = NSNumberFormatter()

let amountTextFieldDelegate = AmountTextFieldDelegate()

required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initTextField()
}

func initTextField(){
self.delegate = amountTextFieldDelegate
currencyFormattor.numberStyle = .CurrencyStyle
currencyFormattor.minimumFractionDigits = 2
currencyFormattor.maximumFractionDigits = 2
}

func setAmount (amount : Double){
let textFieldStringValue = currencyFormattor.stringFromNumber(amount)
self.text = textFieldStringValue
}
}

我的 AmountTextFieldDelegate 看起来像这样

class AmountTextFieldDelegate : NSObject, UITextFieldDelegate{

func textField(textField: AmountTextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

let amount = getAmount() // calculates the amount
textField.setAmount(amount)

return false
}
}

我在shouldChangeCharactersInRange中将UITextField更改为AmountTextField,以便我可以在shouldChangeCharactersInRange中调用setAmount函数。但是当我这样做时,我收到错误 -


方法“textField(:shouldChangeCharactersInRange:replacementString:)”提供的 Objective-C 方法“textField:shouldChangeCharactersInRange:replacementString:”与可选要求方法“textField(:shouldChangeCharactersInRange:”冲突协议(protocol)“UITextFieldDelegate”中的 replacementString:)'

有没有办法可以在shouldChangeCharactersInRange中调用setAmount?

最佳答案

考虑一下:

class AmountTextFieldDelegate : NSObject, UITextFieldDelegate {

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

if let s = textField as? AmountTextField {
let amount = s.getAmount() // calculates the amount
s.setAmount(amount)
}
return true
}
}

关于objective-c - 在 UITextFieldDelegate 函数中使用自定义 UITextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37615170/

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