我試圖通過單擊swift中的按鈕來更改包含圖像的uiimage控件。爲此,我寫了一個簡單的「猜我手捧多少手指」的應用程序。我讀過一些stackoverflow文章,但無法解決問題。下面你可以看到我的代碼和我的用戶界面。我怎樣才能改變點擊更改圖像?如何在swift中點擊按鈕上的uiimage圖像?
這裏是我的代碼:
import UIKit
class ViewController: UIViewController {
@IBOutlet var myImageView: UIImageView!
@IBOutlet var inputField: UITextField!
@IBAction func clickedGuessButtonAction(sender: AnyObject) {
println("Guess button clicked")
var randomX = Int(arc4random()%6)
println("randomX = \(randomX)")
var guess = inputField.text.toInt();
let image0 = UIImage(named: "images/qm.jpg")
let image1 = UIImage(named: "images/tick.jpg")
let image2 = UIImage(named: "images/cross.jpg")
if((inputField.text) != nil){
if(guess == randomX){
println("correct")
myImageView.image=UIImage(named: "tick.jpg") // THIS IS NOT WORKING
myImageView.image=image1 // THIS IS NOT WORKING TOO
inputField.resignFirstResponder();// hides keyboard
}
else
{
println("wrong")
myImageView.image=UIImage(named: "cross.jpg")
inputField.resignFirstResponder();//hides keyboard
}
}
else{
println("invalid input. requires integer only")
inputField.resignFirstResponder();// hides keyboard
}
}
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.
}
}
這是我的UI:
它現在工作。非常感謝你。 – 2014-10-04 11:13:48
完美答案:) – 2015-09-01 11:49:41
從Xcode 9 beta 3上的Swift 4開始,我們現在是否需要包含擴展「.JPEG」? – 2017-07-21 03:39:54