import UIKit
class ViewController: UIViewController {
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var chargeLabel: UILabel!
#IBOutlet weak var bigDogLabel: UILabel!
#IBOutlet weak var cafeImageView: UIImageView!
override func viewDidLoad() {
}
struct DogCafe{
var name: String
var charge: Int
var bigDog: Bool
var cafeImage: UIImage
init(name: String, charge: Int, bigDog: Bool, cafeImage: UIImage) {
self.name = name
self.charge = charge
self.cafeImage = cafeImage
self.bigDog = bigDog
}
func message() {
nameLabel.text = "카페 \(name) 입니다"
chargeLabel.text = "입장료는 \(charge) 입니다"
cafeImageView.image = cafeImage
if bigDog == true {
bigDogLabel.text = "대형견 출입이 가능한 매장입니다"
} else {
bigDogLabel.text = "대형견 출입이 불가능한 매장입니다"
}
}
}
#IBAction func ohdodokButton(_ sender: UIButton) {
let dogCafe = DogCafe(name: "카페 오도독", charge: 3500, bigDog: true, cafeImage: #imageLiteral(resourceName: "ohdodok"))
dogCafe.message()
}
#IBAction func meltingButton(_ sender: UIButton) {
let dogCafe2 = DogCafe(name: "멜팅", charge: 5000, bigDog: false, cafeImage: #imageLiteral(resourceName: "melting"))
dogCafe2.message()
}
}
func message() {
nameLabel.text = "카페 \(name) 입니다"
chargeLabel.text = "입장료는 \(charge) 입니다"
cafeImageView.image = cafeImage
if bigDog == true {
bigDogLabel.text = "대형견 출입이 가능한 매장입니다"
} else {
bigDogLabel.text = "대형견 출입이 불가능한 매장입니다"
}
Instance member 'nameLabel' of type 'ViewController' cannot be used on instance of nested type 'ViewController.DogCafe'
Instance member 'chargeLabel' of type 'ViewController' cannot be used on instance of nested type 'ViewController.DogCafe'
Instance member 'cafeImageView' of type 'ViewController' cannot be used on instance of nested type 'ViewController.DogCafe'
Instance member 'bigDogLabel' of type 'ViewController' cannot be used on instance of nested type 'ViewController.DogCafe'
you can use like below
#IBAction func ohdodokButton(_ sender: UIButton) {
let dogCafe = DogCafe(name: "카페 오도독", charge: 3500, bigDog: true, cafeImage: #imageLiteral(resourceName: "ohdodok"))
setCurrentDogAttributes(currentDog: dogCafe)
}
#IBAction func meltingButton(_ sender: UIButton) {
let dogCafe2 = DogCafe(name: "멜팅", charge: 5000, bigDog: false, cafeImage: #imageLiteral(resourceName: "melting"))
setCurrentDogAttributes(currentDog: dogCafe)
}
func setCurrentDogAttributes(currentDog:DogCafe){
nameLabel.text=currentDog.name
//Set your Values Here
}
Your approach is wrong. You need to read up on separation of concerns. I'd also suggest reading up on the MVC (Model View Controller) design pattern, which is a pretty common way to do development on iOS.
In your code, DogCafe is a model object. It contains data that you want your app to manipulate and display.
A model object should not know anything about how it is being used. It just holds data.
Your view controller should take the model object and display it to its views. One way to handle that is to add a display(cafe:) method to your view controller:
class ViewController: UIViewController {
// The rest of your view controller variables and functions would go here...
func display(cafe: DogCafe) {
nameLabel.text = "카페 \(cafe.name) 입니다"
chargeLabel.text = "입장료는 \(cafe.charge) 입니다"
cafeImageView.image = cafe.cafeImage
if cafe.bigDog == true {
bigDogLabel.text = "대형견 출입이 가능한 매장입니다"
} else {
bigDogLabel.text = "대형견 출입이 불가능한 매장입니다"
}
}
}
Related
I created a class called BlogPost and a tableView. The tableView get filled with many cells and each cell presents the data of a different user (a blogPost object). In each cell there's a button with a phone icon and I want that everytime the user presses on the phone button in each cell, it will call the number of the specific object in that cell. The problem is that in the button function there is no access to the objects value. The line:
var num = blogPost.phone
works inside the setBlogPost function, but not in the button function outside the setBlogPost function :
#IBAction func whatsAppButton(_ sender: Any) {
//doesnt work
var num = blogPost.phone
openWhatsapp(number: num)
}
num gets an error of "Use of unresolved identifier 'blogPost'.
Full code:
import UIKit
class Tavla: UITableViewCell {
#IBOutlet weak var nameLabelTavla: UILabel!
#IBOutlet weak var locationButtonTavla: UIButton!
#IBOutlet weak var phoneButtonTavla: UIButton!
fileprivate let application = UIApplication.shared
func setBLogPost(blogPost: BlogPost) {
nameLabelTavla.text = blogPost.name
if blogPost.elsertext != "" {
locationButtonTavla.backgroundColor = UIColor(red: 135/255, green: 197/255, blue: 113/255, alpha: 0.5)
locationButtonTavla.setTitle("", for: .normal)
}
else{
}
//num works fine
var num = blogPost.phone
}
#IBAction func whatsAppButton(_ sender: Any) {
//num gets an error of "Use of unresolved identifier 'blogPost'
var num = blogPost.phone
openWhatsapp(number: num)
}
func openWhatsapp(number: String){
let urlWhats = "whatsapp://send?phone=\(number)&abid=12354&text=לעדכן מיקום באפליקציה"
if let urlString = urlWhats.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed) {
if let whatsappURL = URL(string: urlString) {
if UIApplication.shared.canOpenURL(whatsappURL) {
UIApplication.shared.open(whatsappURL)
} else {
print("Install Whatsapp")
}
}
}
}
}
Make num a member var:
class Tavla: UITableViewCell {
var num: Int?
// ...
func setBLogPost(blogPost: BlogPost) {
// ...
num = blogPost.phone
}
#IBAction func whatsAppButton(_ sender: Any) {
guard let num = num else { return }
openWhatsapp(number: num)
}
assign the blogPost id to button tag like
button.tag = post.id
in CellForItemAt function, Now you have reference to the blogpost.You can get the clicked blogpost using the button tag like this
#IBAction func whatsAppButton(_ sender: Any) {
let post = blogPostsArray.filter({$0.id == sender.tag})[0]
var num = post.phone
openWhatsapp(number: num)
}
You just set num value in setBlog method as an inner variable. Then num variable can only access the setBlog method. And blogPost object can accessible on setBlog method, not in another method in this class. If you need to access blogPost object in this class then you need to maintain a variable in this class.
Like this:
class Tavla: UITableViewCell {
var blogPost: BlogPost?
...
func setBLogPost(blogPost: BlogPost) {
self.blogPost = blogPost
....
//num works fine
var num = blogPost.phone // because it's access the param value
}
#IBAction func whatsAppButton(_ sender: Any) {
// Now can access the blogPost variable on this class
if let num = self.blogPost?.phone {
openWhatsapp(number: num)
}
}
}
Now the blogPost object can be accessible in whatsAppButton method.
I'm creating a quiz application with multiple categories. If the user would like to select a category, they would "turn on" the switch for that category. Then a Bool value will be set to true if the switch is on and false if it is off. This Bool value would then be sent to the next view controller where if it had a true value, a function would run that would add the array of the selected category's question, to an array that holds the arrays of the selected categories.
Currently, this is how my application functions:
I have a swift file called Question, which creates a class for the basic structure of a question. Then I have another file called QuestionBank which holds a class, and within that class is an array of the questions I created using the class within the Question.swift file. From there, in the view controller for my game, I call the class that holds the array of questions and my code then displays each question, with all its options, in the order that they were called in the array. How would I make it so that the users can access specific questions or a specific group of questions within the array based on user input? I already attempted creating multiple arrays of questions and attempting to call those and combine so the user can be tested on both categories, but I am unable to for some reason.
First View Controller:
import UIKit
class ViewControllerTrivia: UIViewController {
var historySelection = Bool()
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let gameController = segue.destination as! ViewControllerGame
gameController.isHistorySelected = historySelection
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
#IBAction func swipeToHome(_ sender: Any) {
performSegue(withIdentifier: "triviaToHome", sender: ViewControllerHome.self)}
#IBAction func startGame(_ sender: Any) {
performSegue(withIdentifier: "triviaToGame", sender: ViewControllerGame.self)
}
#IBAction func historySelectionSwitch(_ sender: UISwitch) {
if (sender.isOn == true) {
var historySelection = true
print("on")
} else {
var historySelection = false
print("off")
}
}
}
Second View Controller:
import UIKit
class ViewControllerGame: UIViewController {
var isHistorySelected = Bool()
#IBOutlet weak var questionCounter: UILabel!
#IBOutlet weak var scoreLabel: UILabel!
#IBOutlet weak var progressView: UIView!
#IBOutlet weak var questionLabel: UILabel!
//Outlet for Buttons
#IBOutlet weak var optionA: UIButton!
#IBOutlet weak var optionB: UIButton!
#IBOutlet weak var optionC: UIButton!
#IBOutlet weak var optionD: UIButton!
var allQuestions = [(Question(questionText: "History: What does FBLA stand for?", choiceA: "A. Formidable Business Learners of America", choiceB: "B. Future Business Learners of America", choiceC: "C.Future Business Leaders of America", choiceD: "D.Fleeting Business Learners Of America", answer: 3)),]
var historyQuestions = [(Question(questionText: "History: Who was the founder of the FBLA program?", choiceA: "A. Edward D. Miller", choiceB: "B. Conrad N. Hilton", choiceC: "C. Hamden L. Forkner", choiceD: "Elena Daly", answer: 3)) ]
var questionNumber: Int = 0
var score: Int = 0
var selectedAnswer: Int = 0
func questionSelection() {
if isHistorySelected == true{
allQuestions.append(contentsOf: historyQuestions)
}
}
//Making only the top corners of the progress view visible
func roundProgressCorners() {
self.progressView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
}
override func viewDidLoad() {
super.viewDidLoad()
roundProgressCorners()
questionSelection()
updateQuestion()
updateUI()
// Do any additional setup after loading the view.
}
#IBAction func answerPressed(_ sender: UIButton) {
if sender.tag == selectedAnswer{
print("correct")
score += 1
}else {
print("wrong")
}
questionNumber += 1
updateQuestion()
}
func updateQuestion(){
if questionNumber <= allQuestions.count - 1{
questionLabel.text = allQuestions[questionNumber].question
optionA.setTitle(allQuestions[questionNumber].optionA, for: UIControl.State.normal)
optionB.setTitle(allQuestions[questionNumber].optionB, for: UIControl.State.normal)
optionC.setTitle(allQuestions[questionNumber].optionC, for: UIControl.State.normal)
optionD.setTitle(allQuestions[questionNumber].optionD, for: UIControl.State.normal)
selectedAnswer = allQuestions[questionNumber].correctAnswer
updateUI()
}else {
restartQuiz()
performSegue(withIdentifier: "gameToEndScreen", sender: ViewControllerEndScreen.self)
}
}
func updateUI(){
scoreLabel.text = "Score: \(score)"
questionCounter.text = "\(questionNumber + 1)/\(allQuestions.count)"
progressView.frame.size.width = (view.frame.size.width / CGFloat(allQuestions.count)) * CGFloat(questionNumber + 1)
}
func restartQuiz(){
score = 0
questionNumber = 0
updateQuestion()
}
}
For the final result, I would prefer for the user to be able to select which categories they would like to be quizzed on and then the app will then combine the selected categories.
You would have to re-design your data structure, I though of something as below, may be helpful to you or you can get some more idea.
//1. Create an enum of Question Category
enum QuestionCatgory: String{
case Sports = "Sports"
case Politics = "Politicd"
case Science = "Science"
}
//2. Create a Structure that will hold details about each Question, including its category
struct QuestionsDetail{
let question: String
let options: [String]
let currectOption: Int
let category: QuestionCatgory
init(question: String, options: [String], correctOption: Int, category: QuestionCatgory){
self.question = question
self.options = options
self.currectOption = correctOption
self.category = category
}
}
class ViewController: UIViewController {
var questionList: [QuestionsDetail] = []
override func viewDidLoad() {
super.viewDidLoad()
//3. Create data source of your question. Preferably get this data from backend or store it in a Plist or JSON file for better maintainability. In this example its hardcoded
questionList = createDataSource()
//4. Call this method to get questions specific for a Category. You can use this array to populate the question in a ViewController. Use delegate to capture user response to maintain the scorecard and other things
let questionListOfCategory = getQuestionsList(forCategory: .Science)
print("Questions List for:\n\(questionListOfCategory)\n")
}
func getQuestionsList(forCategory category: QuestionCatgory) -> [QuestionsDetail]{
var questionListOfCategory: [QuestionsDetail] = []
for question in questionList {
if question.category.rawValue == category.rawValue{
questionListOfCategory.append(question)
}
}
return questionListOfCategory
}
func createDataSource() -> [QuestionsDetail]{
let questionDetail1 = QuestionsDetail(question: "Question1", options: ["Option1 A", "Option1 B", "Option1 C", "Option1 D"], correctOption: 2, category: .Sports)
let questionDetail2 = QuestionsDetail(question: "Question2", options: ["Option2 A", "Option2 B", "Option2 C", "Option2 D"], correctOption: 4, category: .Politics)
let questionDetail3 = QuestionsDetail(question: "Question3", options: ["Option3 A", "Option3 B", "Option3 C", "Option3 D"], correctOption: 1, category: .Science)
let questionDetail4 = QuestionsDetail(question: "Question4", options: ["Option4 A", "Option4 B", "Option4 C", "Option4 D"], correctOption: 3, category: .Sports)
let questionDetail5 = QuestionsDetail(question: "Question5", options: ["Option5 A", "Option5 B", "Option5 C", "Option5 D"], correctOption: 4, category: .Politics)
var questionList: [QuestionsDetail] = []
questionList.append(questionDetail1)
questionList.append(questionDetail2)
questionList.append(questionDetail3)
questionList.append(questionDetail4)
questionList.append(questionDetail5)
return questionList
}
}
I am new here and would like to ask a question that has been working for me for days. I'm just learning Swift 4 and I've come quite a long way. I really do not know what to do any more, and my books on swift do not help me either.
I have created a small testapp, in which should simply be charged.
There are 5 view controllers. The first one has 4 buttons to get to one of the other 4 and to enter a number there in a text box. This number is then output in the first viewcontroller in a label. The numbers are displayed and even the last entered number is displayed again after a restart of the app.
But now I want to charge off the numbers in the first viewcontroller. How can I fix the code?
My Viewports:
my viewports
code from main viewport:
import UIKit
class ViewController: UIViewController, sendValue1, sendValue2, sendValue3, sendValue4 {
#IBOutlet weak var value1: UILabel!
#IBOutlet weak var value2: UILabel!
#IBOutlet weak var value3: UILabel!
#IBOutlet weak var value4: UILabel!
#IBOutlet weak var calculatedValue1: UILabel! // here i want to see the calculated value like from the label 1-4...value1 + value2 + value3 + value4 = ???
#IBOutlet weak var calculatedValue2: UILabel! // here the same like in claculatedValue1 value but with "-" or "*" or something else...
func value1Data(data: String) {
value1.text = data
UserDefaults.standard.set(value1.text, forKey: "value1")
}
func value2Data(data: String) {
value2.text = data
UserDefaults.standard.set(value2.text, forKey: "value2")
}
func value3Data(data: String) {
value3.text = data
UserDefaults.standard.set(value3.text, forKey: "value3")
}
func value4Data(data: String) {
value4.text = data
UserDefaults.standard.set(value4.text, forKey: "value4")
}
override func viewDidAppear(_ animated: Bool) {
if let lastValue1Data = UserDefaults.standard.object(forKey: "value1") as? String {
value1.text = lastValue1Data
}
if let lastValue2Data = UserDefaults.standard.object(forKey: "value2") as? String {
value2.text = lastValue2Data
}
if let lastValue3Data = UserDefaults.standard.object(forKey: "value3") as? String {
value3.text = lastValue3Data
}
if let LastValue4Data = UserDefaults.standard.object(forKey: "value4") as? String {
value4.text = LastValue4Data
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "VC1" {
let SendingVC1: Value1ViewController = segue.destination as! Value1ViewController
SendingVC1.delegate = self
}
if segue.identifier == "VC2" {
let SendingVC2: Value2ViewController = segue.destination as! Value2ViewController
SendingVC2.delegate = self
}
if segue.identifier == "VC3" {
let SendingVC3: Value3ViewController = segue.destination as! Value3ViewController
SendingVC3.delegate = self
}
if segue.identifier == "VC4" {
let SendingVC4: Value4ViewController = segue.destination as! Value4ViewController
SendingVC4.delegate = self
}
}
#IBAction func unwindToView1(_ segue: UIStoryboardSegue) {
}
and the code from one of the other four:
import UIKit
protocol sendValue1 {
func value1Data(data: String)
}
class Value1ViewController: UIViewController {
var delegate: sendValue1? = nil
#IBOutlet weak var textValue1: UITextField!
#IBAction func done(_ sender: Any) {
if delegate != nil {
if textValue1.text != nil {
let data = textValue1.text
delegate?.value1Data(data: data!)
dismiss(animated: true, completion: nil)
}
}
}
why is the result always nil here?
let a = Float(value3.text!) ?? 0
let b = Float(value4.text!) ?? 0
let SUM = a + b
calculatedValue1.text = "\(SUM)" + "m"
No matter what I do, the numbers are not processed ...
How do you get a reference property to trigger a property observer?
In order to demonstrate my problem I wrote a simple MVC program with one button and one label. The button increments a counter in the model and displays the value of the counter in the label in the view controller.
The problem is that the counter increment (in the model) does not trigger the didSet observer ( in the view controller)
Here is the model file:
import Foundation
class MvcModel {
var counter: Int
var message: String
init(counter: Int, message: String) {
self.counter = counter
self.message = message
}
}
// create instance
var model = MvcModel(counter: 0, message: "" )
// counting
func incrementCounter() {
model.counter += 1
model.message = "Counter Value: \(model.counter)"
//print(model.message)
}
Here is the view controller file:
import Cocoa
class ViewController: NSViewController {
let model1 = model
var messageFromModel = model.message {
didSet {
updateDisplayCounterLabel()
}
}
// update Label
func updateDisplayCounterLabel() {
DisplayCounterLabel.stringValue = model1.message
}
// Label
#IBOutlet weak var DisplayCounterLabel: NSTextField! {
didSet {
DisplayCounterLabel.stringValue = "counter not started"
}
}
// Button
#IBAction func IncrementButton(_ sender: NSButton) {
incrementCounter()
print("IBAction: \(model1.message)")
}
}
I guess the problem is linked to reference property (as I have been able to make this program work with a model based on a struct).
I would appreciate if someone could tell me how to deal with property observers and reference property and make this kind of MVC work as I plan to use it in real programs.
You could create a delegate for MvcModel
protocol MvcModelDelegate {
func didUpdateModel(counter:Int)
}
next you add a delegate property to MvcModel
class MvcModel {
var counter: Int {
didSet {
delegate?.didUpdateModel(counter: counter)
}
}
var message: String
var delegate: MvcModelDelegate?
init(counter: Int, message: String) {
self.counter = counter
self.message = message
}
}
then you make the ViewController class conform to MvcModelDelegate and finally you set model.delegate = self into the viewDidLoad
class Controller: UIViewController, MvcModelDelegate {
let model = MvcModel(counter: 0, message: "hello")
override func viewDidLoad() {
super.viewDidLoad()
self.model.delegate = self
}
func didUpdateModel(counter: Int) {
print("new value for counter \(counter)")
}
}
In case someone is interested here is the code as suggested by Noam.
Model File:
import Foundation
protocol MvcModelDelegate {
func didUpDateModel(message: String)
}
class MvcModel {
var counter: Int
var message: String {
didSet {
delegate?.didUpDateModel(message: message)
}
}
var delegate: MvcModelDelegate?
init(counter: Int, message: String) {
self.counter = counter
self.message = message
}
}
// create instance
var model = MvcModel(counter: 0, message: "" )
// counting
func incrementCounter() {
model.counter += 1
model.message = "Counter Value: \(model.counter)"
}
}
View Controller File
import Cocoa
class ViewController: NSViewController, ModelDelegate {
// communication link to the model
var model1 = model
var messageFromModel = messageToLabel
override func viewDidLoad() {
super.viewDidLoad()
self.model1.delegate = self
}
// update display
func didUpdateModel(message: String) {
//self.Label1.stringValue = model1.message
self.Label1.stringValue = messageFromModel
}
// Label
#IBOutlet weak var Label1: NSTextField! {
didSet {
Label1.stringValue = " counter not started"
}
}
// Button
#IBAction func testButton(_ sender: NSButton) {
incrementCounter()
}
}
My code is randomly generating 2 separate images on the same interface controller. I need to check if the images match each other, but i'm unsure how to go about this as they are being randomly generated. I have tried writing if statements such as:
if blueColour.setBackgroundImageNamed("colour\(randomImage).jpg") == mainBackgroundColour.setBackgroundImageNamed("mainColour\(randomMainBackground).jpg") {
println("they match")
} else {
println("they dont match")
}
but it doesn't seem to work, i get an error saying "binary operator '==' cannot be applied to two Void operands"
My code is below:
#IBOutlet var blueColour: WKInterfaceButton!
#IBOutlet var pinkColour: WKInterfaceButton!
#IBOutlet var greenColour: WKInterfaceButton!
#IBOutlet var yellowColour: WKInterfaceButton!
#IBOutlet var mainBackgroundColour: WKInterfaceGroup!
#IBOutlet var scoreLabel: WKInterfaceLabel!
var randomImage = UInt32()
var randomMainBackground = UInt32()
#IBAction func onePressedTest() {
if blueColour.setBackgroundImageNamed("colour\(randomImage).jpg") == mainBackgroundColour.setBackgroundImageNamed("mainColour\(randomMainBackground).jpg") {
println("they match")
} else {
println("they dont match")
}
randomImage = arc4random_uniform(4)
blueColour.setBackgroundImageNamed("colour\(randomImage).jpg")
randomImage = arc4random_uniform(4)
pinkColour.setBackgroundImageNamed("colour\(randomImage).jpg")
randomImage = arc4random_uniform(4)
greenColour.setBackgroundImageNamed("colour\(randomImage).jpg")
randomImage = arc4random_uniform(4)
yellowColour.setBackgroundImageNamed("colour\(randomImage).jpg")
randomMainBackground = arc4random_uniform(4)
mainBackgroundColour.setBackgroundImageNamed("mainColour\(randomMainBackground).jpg")
}
NEW AMENDED CODE 20.04.2015:
import WatchKit
import Foundation
protocol WKInterfaceComparableImage {
func getImage()->UIImage;
func equalsImage(comparableWKObject:WKInterfaceComparableImage)->Bool;
}
class WKInterfaceButtonComparable : WKInterfaceButton, WKInterfaceComparableImage {
private var image:UIImage?;
override func setBackgroundImage(image: UIImage?) {
self.image = image;
super.setBackgroundImage(image);
}
func equalsImage(comparableWKObject: WKInterfaceComparableImage)->Bool {
return self.image === comparableWKObject.getImage();
}
func getImage() -> UIImage {
return image!;
}
}
class WKInterfaceGroupComparable : WKInterfaceButton, WKInterfaceComparableImage {
private var image:UIImage?;
override func setBackgroundImage(image: UIImage?) {
self.image = image;
super.setBackgroundImage(image);
}
func equalsImage(comparableWKObject: WKInterfaceComparableImage)->Bool {
return self.image === comparableWKObject.getImage();
}
func getImage() -> UIImage {
return image!;
}
}
class ImageProvide {
private let MAX_RANDOM_NUMBER:UInt32 = 4
static let shared:ImageProvide = ImageProvide();
var images:[UIImage];
private init() {
images = [];
for i in 1...MAX_RANDOM_NUMBER {
//get image with the best way to you
images.append(UIImage(named: "colour\(i).jpg")!);
}
}
func getRandomImage()->UIImage {
let randomImage = arc4random_uniform(MAX_RANDOM_NUMBER);
return getImage(id: Int(randomImage));
}
func getImage(#id:Int)->UIImage {
return images[id];
}
}
class InterfaceController: WKInterfaceController {
#IBOutlet var blueColour: WKInterfaceButtonComparable!
#IBOutlet var pinkColour: WKInterfaceButtonComparable!
#IBOutlet var greenColour: WKInterfaceButtonComparable!
#IBOutlet var yellowColour: WKInterfaceButtonComparable!
#IBOutlet var mainBackgroundColour: WKInterfaceGroupComparable!
#IBOutlet var scoreLabel: WKInterfaceLabel!
var randomImage = UInt32()
var randomMainBackground = UInt32()
var score:Int = 1
#IBAction func onePressedTest() {
if blueColour.equalsImage(mainBackgroundColour) || pinkColour.equalsImage(mainBackgroundColour) || greenColour.equalsImage(mainBackgroundColour) || yellowColour.equalsImage(mainBackgroundColour) {
println("they match")
scoreLabel.setText("\(score)")
score++
} else {
println("they dont match")
}
blueColour.setBackgroundImage(ImageProvide.shared.getRandomImage())
pinkColour.setBackgroundImage(ImageProvide.shared.getRandomImage())
greenColour.setBackgroundImage(ImageProvide.shared.getRandomImage())
yellowColour.setBackgroundImage(ImageProvide.shared.getRandomImage())
mainBackgroundColour.setBackgroundImage(ImageProvide.shared.getRandomImage())
I made an example what I think can help you find the way to resolve your issues, I created class custom with comparable power to help your work. I do it very fast, and I don't have way to test for you, but you can see the concept to help you create a solution. I hope so helped you with my example.
ComparableImage is the key to compare, this protocol can do your mission.
WKInterfaceButtonComparable extends WKInterfaceButton and with this you can save the current image to compare after, I did same with WKInterfaceGroupComparable.
ImageProvide is important because this will manage your images, there you need code your logic about images and with this Singleton you can preload your images and send to your WK components. I hope it help too.
protocol WKInterfaceComparableImage {
func getImage()->UIImage;
func equalsImage(comparableWKObject:WKInterfaceComparableImage)->Bool;
}
class WKInterfaceButtonComparable : WKInterfaceButton, WKInterfaceComparableImage {
private var image:UIImage?;
override func setBackgroundImage(image: UIImage?) {
self.image = image;
super.setBackgroundImage(image);
}
func equalsImage(comparableWKObject: WKInterfaceComparableImage)->Bool {
return self.image === comparableWKObject.getImage();
}
func getImage() -> UIImage {
return image!;
}
}
class WKInterfaceGroupComparable : WKInterfaceButton, WKInterfaceComparableImage {
private var image:UIImage?;
override func setBackgroundImage(image: UIImage?) {
self.image = image;
super.setBackgroundImage(image);
}
func equalsImage(comparableWKObject: WKInterfaceComparableImage)->Bool {
return self.image === comparableWKObject.getImage();
}
func getImage() -> UIImage {
return image!;
}
}
class ImageProvide {
private let MAX_RANDOM_NUMBER:UInt32 = 4
static let shared:ImageProvide = ImageProvide();
var images:[UIImage];
private init() {
images = [];
for i in 1...MAX_RANDOM_NUMBER {
//get image with the best way to you
images.append(UIImage(named: "colour\(i).jpg")!);
}
}
func getRandomImage()->UIImage {
let randomImage = arc4random_uniform(MAX_RANDOM_NUMBER);
return getImage(id: Int(randomImage));
}
func getImage(#id:Int)->UIImage {
return images[id];
}
}
class InterfaceController: WKInterfaceController {
#IBOutlet var blueColour: WKInterfaceButtonComparable!
#IBOutlet var pinkColour: WKInterfaceButtonComparable!
#IBOutlet var greenColour: WKInterfaceButtonComparable!
#IBOutlet var yellowColour: WKInterfaceButtonComparable!
#IBOutlet var mainBackgroundColour: WKInterfaceGroupComparable!
#IBOutlet var scoreLabel: WKInterfaceLabel!
var randomImage = UInt32()
var randomMainBackground = UInt32()
var score:Int = 1
#IBAction func onePressedTest() {
if blueColour.equalsImage(mainBackgroundColour) {
println("they match")
} else {
println("they dont match")
}
blueColour.setBackgroundImage(ImageProvide.shared.getRandomImage())
pinkColour.setBackgroundImage(ImageProvide.shared.getRandomImage())
greenColour.setBackgroundImage(ImageProvide.shared.getRandomImage())
yellowColour.setBackgroundImage(ImageProvide.shared.getRandomImage())
mainBackgroundColour.setBackgroundImage(ImageProvide.shared.getRandomImage())
}
}