Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

ios - Error using Swift - Instance member cannot be used on type 'ViewController'

I've been trying to make an app in Xcode 7 using Swift and I'm trying to convert numbers inside a textfield to an integer using this code, let a = Int(percentLabel.text!)

But everytime I try this I get an error that says Instance Member 'percentLabel' cannot be used on type 'ViewController'

I'm not sure why I'm getting this error, maybe it's a bug which I've already found in Xcode 7.

Here is my full code.

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) {


    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You cannot have these two lines outside of a function call in a class

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

You cannot intialise a property to a value of another property, you cannot set a variable's default value to that of another property. you would usually do this in a function like viewDidLoad or viewWillAppear. Arsen's answer should also work as it will try to get the value lazily, or as you request it.

let myString = percentLabel would also not return the text, you'd need to do let myString = percentLabel.text but you cannot assign this value like a property. you'll need to put his code in the body of a function


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...