比较值

时间:2015-12-27 17:55:26

标签: swift view colors

我创建了一个用作背景的视图,我希望在标签文本大于或小于变量数时更改其颜色。脚本没问题,但颜色没有变化。

提前致谢。

导入UIKit

类ViewController:UIViewController,UITextFieldDelegate {

@IBOutlet weak var localName: UITextField!

@IBOutlet weak var localNameLabel: UILabel!

@IBOutlet weak var localTemp: UILabel!

@IBAction func getData(sender: AnyObject) {
    getWeatherData("http://api.openweathermap.org/data/2.5/weather?q=" + localName.text! + "")
}


@IBOutlet weak var fundo: UIView!

override func viewDidLoad() {
    super.viewDidLoad()
    getWeatherData("http://api.openweathermap.org/data/2.5/weather?q=London")
    // 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.
}


func getWeatherData(urlString: String){
    let url = NSURL (string: urlString)

    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) in
        dispatch_async(dispatch_get_main_queue(), {
            self.setLabels(data!)
        })
    }

    task.resume()
}

func setLabels(weatherData: NSData) {

    do {
        let json = try NSJSONSerialization.JSONObjectWithData(weatherData, options:NSJSONReadingOptions.MutableContainers) as! NSDictionary
        print(json)

        //localNameLabel.text = json[("name")] as? String
        if let name = json[("name")] as? String {
            localNameLabel.text = name
        }

        if let main = json[("main")] as? NSDictionary {
            if let temp = main[("temp")] as? Double {
                //convert kelvin to celsius
                let ft = (temp - 273.15)

                let myString = ft.description

                localTemp.text = myString

                self.changeColor()

            }
        }


    } catch let error as NSError {
        print(error)
    }

var number : Float
func changeColor(){

    number = 19.0

    if(Float(localTemp.text!) < number){
        fundo.backgroundColor = .blueColor()
    }else{
        fundo.backgroundColor = .orangeColor()
        }
    }

}

}

编辑发布整个脚本

1 个答案:

答案 0 :(得分:0)

在视图控制器中,您需要添加UITextFieldDelegate,这将允许您访问与文本字段相关的方法。视图控制器的顶部应如下所示:

class ViewController: UIViewController,UITextFieldDelegate  //set delegate to class 

然后,您需要在viewDidLoad中将文本字段的委托设置为self,并在文本字段更改时添加目标:

override func viewDidLoad() {
    super.viewDidLoad()
    localTemp.delegate = self     //set delegate to this vc
    localTemp.addTarget(self, action: "textFieldDidChange:", forControlEvents: UIControlEvents.EditingChanged)
}

然后,您可以实现此方法,该方法将在每次按键时运行,您需要调用您的changeColor()方法,如上所述:

func textFieldDidChange(textField: UITextField) {
    self.changeColor()
}