ios - 将输入数字存储在文本框中的变量中

标签 ios swift variables textbox

在我的应用程序中,我有一个文本框,应该用 Double 填充,数字应该保存到一个变量中,但出现错误。 我将文本框拖放到 ViewController.swift 中,因此它应该被链接。我创建了一个 @IBOutlet。我调用了文本框 mmolText 和变量 mmol。 我试过类似的东西:var mmol = mmolText.text 但它显示错误:

'ViewController.Type' does not have a member named 'mmolText'.

有什么问题?我该如何解决?除了文本框内容的类型是字符串,但我应该将其转换为 Double

screenshot

这里ViewController.swift的代码是:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var mmolText: UITextField!
    var mmol = mmolText.text
    @IBOutlet weak var mmolLabel: UILabel!
    @IBOutlet weak var mgLabel: UILabel!
    @IBAction func convertBM(sender: AnyObject) {

    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

最佳答案

似乎我们可能只是希望 mmol 存在作为从 mmolText 文本字段中获取 text 属性的便捷方式,对吧?那么为什么不使用计算属性:

var mmol: String {
    get {
        return mmolText.text ?? ""
    }
    set {
        mmolText.text = newValue
    }
}

get 使用了 nil 合并运算符。 UITextFieldtext 属性尚未使用 Objective-C nullability annotations 更新然而,所以我们需要处理它可能返回 nil 的情况。

如果我们希望它是readonly,我们可以简单地省略set部分。


如果我们希望它是一个Double,我们可以修改上面的计算属性使其看起来更像这样:

var mmol: Double {
    get {
        return ((mmolText.text ?? "0") as NSString).doubleValue
    }
    set {
        mmolText.text = String("%f", newValue)
    }
}

再一次,如果我们希望它是readonly,我们可以简单地省略 set 一半。当然,在使用此 set 方法时,可以使用格式字符串来使 double 的字符串版本完全按照您的意图显示。

关于ios - 将输入数字存储在文本框中的变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30293170/

相关文章:

ios - 在 iOS 8 应用程序中应该如何组织字符串?

swift - 在 Swift 中使用不安全指针的原因,尤其是在 Metal 中

ios - 从 UIButton 获取对 UIBarButtonItem 的引用?

ios - 如何显示和滚动谷歌地图的特定 View 范围?我们看不到和滚动的 map 的其他部分

ios - 取消选中后 UIScrollView 不滚动 "Adjust scroll view insets"xcode 6

ios - 如何在 Swift 中将一个属性分配给多个变量?

javascript - 显示随机 div onclick

r - 函数 (x,y),x 和 y 都变化

java - 局部变量 NullPointerException

iOS Objective-C 逻辑或键盘类型