【问题标题】:Using custom UITextField in UITextFieldDelegate functions在 UITextFieldDelegate 函数中使用自定义 UITextField
【发布时间】:2016-06-03 13:04:10
【问题描述】:

我正在尝试在 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 函数。但是当我这样做时,我得到了错误 -


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

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

【问题讨论】:

  • 设置金额有什么作用?您正在尝试覆盖委托中已存在的方法
  • 不,只是格式化金额并将其添加到文本字段中。我添加了那段代码以使其更清晰

标签: objective-c swift uitextfield uitextfielddelegate


【解决方案1】:

考虑一下:

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
    }
}

【讨论】:

  • @Richa 其实我还在想为什么你的版本不起作用。我会尝试向 Swift 社区记录一个错误。让我们看看他们会回复什么。
  • 我也想知道,我觉得我已经在Objective C中做到了这一点
  • 是的,Obj-C 等效编译正常
猜你喜欢
  • 1970-01-01
  • 2011-04-03
  • 1970-01-01
  • 2011-06-22
  • 2012-05-29
  • 2011-10-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-27
相关资源
最近更新 更多