Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/112.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 使用Swift时出错-实例成员不能用于类型';ViewController';_Ios_Swift - Fatal编程技术网

Ios 使用Swift时出错-实例成员不能用于类型';ViewController';

Ios 使用Swift时出错-实例成员不能用于类型';ViewController';,ios,swift,Ios,Swift,我一直在尝试使用Swift在Xcode 7中制作一个应用程序,并尝试使用以下代码将文本字段中的数字转换为整数,let a=Int(percentLabel.text!) 但每次尝试此操作时,都会出现一个错误,即实例成员'percentLabel'不能用于类型'ViewController' 我不确定为什么会出现这个错误,可能是我在Xcode 7中发现的一个bug 这是我的全部代码 import UIKit class ViewController: UIViewController {

我一直在尝试使用Swift在Xcode 7中制作一个应用程序,并尝试使用以下代码将文本字段中的数字转换为整数,
let a=Int(percentLabel.text!)

但每次尝试此操作时,都会出现一个错误,即
实例成员'percentLabel'不能用于类型'ViewController'

我不确定为什么会出现这个错误,可能是我在Xcode 7中发现的一个bug

这是我的全部代码

import UIKit

class ViewController: UIViewController {
    @IBOutlet var tipSlider: UISlider!
    @IBOutlet var splitSlider: UISlider!
    @IBOutlet var billAmount: UITextField!
    @IBOutlet var totalLabel: UILabel!
    @IBOutlet var tipTotal: UILabel!
    @IBOutlet var totalPerPerson: UILabel!
    @IBOutlet var percentLabel: UILabel!
    @IBOutlet var splitLabel: UILabel!

    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.
    }
    let a = Int(percentLabel.text!)

    @IBAction func tipChanged(sender: AnyObject) {
        let currentValue = Int(tipSlider.value)
        percentLabel.text = "\(currentValue)"
    }

    @IBAction func splitChanged(sender: AnyObject) {
        let currentValue = Int(splitSlider.value)
        splitLabel.text = "\(currentValue)"
    }

    @IBAction func amountChanged(sender: AnyObject) {


    }
}

在类的函数调用之外不能有这两行

let myString = percentLabel
let myInt: Int? = Int(myString)
不能将属性初始化为其他属性的值,也不能将变量的默认值设置为其他属性的值。您通常会在viewDidLoad或ViewWillDisplay之类的函数中执行此操作。Arsen的回答也应该起作用,因为它会懒散地获取值,或者按照您的要求


let-myString=percentLabel
也不会返回文本,您需要执行
let-myString=percentLabel.text
操作,但不能像属性一样分配此值。您需要将他的代码放入函数体中

此代码每次调用时都会返回一个新值。我想这就是你想要的

var myInt: Int? {
    return Int(percentLabel.text!)
}
而不是

let myString = percentLabel
let myInt: Int? = Int(myString)

我对代码进行了更改,而不是让myString=percentLabel让myInt:Int?=Int(myString)我本想让a=Int(percentLabel.text!)给我同样的错误。如果你能多解释一点,我将不胜感激,因为我在Swift或编程方面没有经验,我已经更新了答案。这只是因为您在类上创建的属性依赖于另一个属性的值。我认为你做不到。事实上,我想我已经弄明白了。非常感谢!在这种情况下,阿森的回答应该对你有帮助。否则,它将取决于您希望设置值的时间。