ios - Swift 中的 UITextField `setText`

标签 ios swift

使用 Objective-C,我可以通过以下代码覆盖 setText 函数。 textUITextField 的属性,我将其子类化以用于某些自定义 UI 设计。

- (void)setText:(NSString *)text
{
   [super setText:text];
   ....
}

我的问题是,Swift 如何做这样的事情?

我用Swift编程时没有setText这个函数。如何使用 Swift 覆盖属性的 settergetter 方法?

最佳答案

在这种情况下,您可以使用变量观察器。

var variableName: someType = expression {
    willSet(valueName) {
    // code called before the value is changed
    }
    didSet(valueName) {
    // code called after the value is changed
    }
}

一个实际的例子。

“class StepCounter {
    var totalSteps: Int = 0 {
        willSet(newTotalSteps) {
            print("About to set totalSteps to \(newTotalSteps)")
        }
        didSet {
            if totalSteps > oldValue  {
                print("Added \(totalSteps - oldValue) steps")
            }
        }
    }
}”

摘自:Apple Inc.“The Swift Programming Language (Swift 2.1 Prerelease)”。电子书。 https://itun.es/us/k5SW7.l

关于ios - Swift 中的 UITextField `setText`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35406558/

相关文章:

ios - 在 SWIFT 中推送之前如何加载 View ?

ios - AFNetworking 故障 block

ios - 神秘崩溃与 NSString 方法 rangeOfComposedCharacterSequenceAtIndex :

ios - Swift UITableViewCell subview 布局更新延迟

ios - 为什么我的 CGImage 在 setNeedsDisplay 后不能正确显示

ios - iOS Swift 中的 core.async channel 用于解耦组件

ios - Mapbox iOS : User location not showing after turning device location service on

ios - 如何在 Swift 中以编程方式创建约束?

ios - 在 ObjC 中工作,而不是在 swift 中工作。我在 swift 中使用 JSON 解析有什么问题

SwiftUI:将分段控件(选择器)放在搜索栏下方的导航栏中?