UIImageView UIImage String Value Swift 4 - swift

I'm trying to get the String value from a UIImageView's UIImage when touchesBegan.
here is the entire viewcontroller code.
import UIKit
class ViewController: UIViewController {
//MARK: Outlets
#IBOutlet weak var imageOne: UIImageView!
#IBOutlet weak var imageTwo: UIImageView!
#IBOutlet weak var myText: UILabel!
let imagesArray = ["banaan", "auto", "kip", "boom" ]
var questionArray: [String] = []
var touchArray: [CGPoint] = []
var itemOne: Int!
var itemTwo: Int!
override func viewDidLoad() {
super.viewDidLoad()
setupQuestions()
setupImages()
}
//MARK: Randomizing The Lable Question
fileprivate func setupQuestions() {
let firstRandomizer = arc4random_uniform(UInt32(imagesArray.count))
let secondRandomizer = arc4random_uniform(UInt32(imagesArray.count))
itemOne = Int(firstRandomizer)
itemTwo = Int(secondRandomizer)
if itemOne == itemTwo && itemTwo != 0 {
itemTwo -= 1
} else if itemOne == itemTwo && itemTwo == 0 {
itemTwo += 1
}
myText.text = """
selecteer de \(imagesArray[itemOne].capitalized)
voor dat je de \(imagesArray[itemTwo].capitalized) selecteert
"""
}
//Mark: setup images and randomizeing
fileprivate func setupImages() {
imageOne.image = UIImage(named: imagesArray[itemOne])
imageTwo.image = UIImage(named: imagesArray[itemTwo])
}
//MARK: Button Randomizer
#IBAction func nextBtnWasPressed(_ sender: Any) {
setupQuestions()
setupImages()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//Get image stringvalue to compare it with the question array
}
}

You can try
self.myImageView.image = UIImage(myImageArray[0])
self.myImageView.tag = 0
then inside touches
myImageArray[self.myImageView.tag]
you can also declare a var for a good pattern following
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
print("itemOne name \(myImageArray[itemOne]) , itemTwo name \(myImageArray[itemTwo])")
}

Related

On pressed touch Hide/Show UIImage, and count number down from 10 to 0

On every pressed touch I want UILabel to count number down one by one from 10 to 0.
Also when pressed I want to show UIImageView: "MyRocketWith", and when release the pressed touch I want to show UIImageView: "MyRocket".
class ViewController: UIViewController {
#IBOutlet weak var MyRocket: UIImageView!
#IBOutlet weak var MyRocketWith: UIImageView!
#IBOutlet weak var Countdown: UILabel!
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch: UITouch? = touches.first
if touch?.view != self.MyRocket {
self.MyRocketWith.isHidden = true
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
The below code shows and hides the UIImageView on click of UILabel
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var MyRocketWith: UIImageView!
#IBOutlet weak var CountDownLabel: UILabel!
#IBOutlet weak var MyRocket: UIImageView!
var count = 10
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapFunction))
CountDownLabel.isUserInteractionEnabled = true
CountDownLabel.addGestureRecognizer(tap)
MyRocket.isHidden = false
MyRocketWith.isHidden = true
MyRocketWith.tag=0
}
#IBAction func tapFunction(sender: UITapGestureRecognizer) {
print("tap working")
count = count-1
CountDownLabel.text = String(count)
if MyRocketWith.tag == 0
{
MyRocket.isHidden = true
MyRocketWith.isHidden = false
MyRocketWith.tag=1
}
else
{
MyRocket.isHidden = false
MyRocketWith.isHidden = true
MyRocketWith.tag=0
}
}
}

View Controller doesn't find a func member

I'm getting this error:
Value of type 'DiscountVC' has no member 'calculateTotal'. And I have no clue why. Basically, I'm trying to make this calculator:
It should work as soon as you insert any value on the discountTF. Also, I have some pre-discounted buttons that just edit the discount value. The subtotalLabel value comes from another ViewController. For testing purposes, I'm using an initial value of 999.9.
import UIKit
class DiscountVC: UIViewController {
#IBOutlet var numericKeyboardView: UIView!
#IBOutlet var subtotalLabel: UILabel!
#IBOutlet var discountTF: UITextField!
#IBOutlet var totalLabel: UILabel!
var subtotal : Double = 999.9
var discount : Double = 0.0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
addKeyboard(view: numericKeyboardView)
subtotal = 999.9
discount = 0.0
discountTF.addTarget(self, action: #selector(self.calculateTotal(_:)), for: UIControl.Event.editingChanged)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
func calculateTotal() {
let totalDouble = Double(subtotal) - Double(discountTF.text!)!
totalLabel.text = String(totalDouble)
}
func addKeyboard(view: UIView) {
let numericKeyboard = KeyboardVC(nibName: "NumericKeyboardVC", bundle: nil)
view.addSubview(numericKeyboard.view)
addChild(numericKeyboard)
}
#IBAction func fivePercentedButtonPressed(_ sender: Any) {
discount = Double(discountTF.text!)! * 0.05
discountTF.text = "\(discount)"
print(discount)
}
#IBAction func tenPercentButtonPressed(_ sender: Any) {
discount = Double(discountTF.text!)! * 0.1
discountTF.text = "\(discount)"
print(discount)
}
#IBAction func fifteenPercentButtonPressed(_ sender: Any) {
discount = Double(discountTF.text!)! * 0.15
discountTF.text = "\(discount)"
print(discount)
}
#IBAction func twentyPercentButtonPressed(_ sender: Any) {
discount = Double(discountTF.text!)! * 0.2
discountTF.text = "\(discount)"
print(discount)
}
#IBAction func goButton(_ sender: Any) {
}
}
Change to
#objc func calculateTotal(_ tex:UITextField){ --- }

Swift-4 MacOS Detect Mouse Wheel Scroll over NSTextField?

I have a NSTextField on a MacOS app with Swift-4
Its purpose is for the user to input a number.
Is there a way to change the number based on scroll up or scroll down of a mouse wheel?
You can just override scrollWheel(with event: NSEvent) method and check if the event.deltaY is positive or negative and increase or decrease the textField value:
import Cocoa
class ViewController: NSViewController {
#IBOutlet weak var textField: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
textField.stringValue = "0"
}
override func scrollWheel(with event: NSEvent) {
super.scrollWheel(with: event)
if var value = Int(textField.stringValue) {
if event.deltaY > 0 { value += 1 }
if event.deltaY < 0 { value -= 1 }
textField.stringValue = String(value)
print(value)
}
}
}
If you would like to just change the field that has focus you can use the view window fieldEditor:
if let text = view.window?.fieldEditor(false, for: nil) {
if var value = Int(text.string) {
if event.deltaY > 0 { value += 1 }
if event.deltaY < 0 { value -= 1 }
text.string = String(value)
print(value)
}
}
If you would like to restrict the scroll to just a particular field you would need to set your view controller as the delegate of it and compare its delegate against the textfield object:
import Cocoa
class ViewController: NSViewController, NSTextFieldDelegate {
#IBOutlet weak var textField1: NSTextField!
#IBOutlet weak var textField2: NSTextField!
override func viewDidAppear() {
super.viewDidAppear()
textField1.delegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
textField1.stringValue = "0"
textField2.stringValue = "0"
}
override func scrollWheel(with event: NSEvent) {
super.scrollWheel(with: event)
NSSound(named: "Tink")?.stop
if view.window?.firstResponder?.textView?.delegate === textField1,
let text = view.window?.fieldEditor(false, for: nil),
var value = Int(text.string) {
if event.deltaY < 0 { value += 1 }
if event.deltaY > 0 { value -= 1 }
NSSound(named: "Tink")?.play()
text.string = String(value)
print(value)
}
}
}
extension NSResponder {
var textView: NSTextView? { return self as? NSTextView }
}

How do I dismiss keyboard with a touch? touchesBegan not workig

According to everything I've read here, I should override touchesBegan() to dismiss the keyboard (in my case DatePicker). Unfortunately touching the screen does not dismiss the DatePicker. Touching other UI elements like the UISteppers dismisses the keyboard just fine, and it is using the same function of CloseKeyboard()
class RecordWorkoutTableViewController: UITableViewController, UITextFieldDelegate {
#IBOutlet weak var dateTextField: UITextField!
#IBOutlet weak var weightLabel: UILabel!
#IBOutlet weak var setOneLabel: UILabel!
#IBOutlet weak var setTwoLabel: UILabel!
#IBOutlet weak var weightStepper: UIStepper!
#IBOutlet weak var setOneStepper: UIStepper!
#IBOutlet weak var setTwoStepper: UIStepper!
var newDate: NSDate? {
didSet {
dateTextField.text = NSDateToPrettyString(newDate!)
}
}
var newWeight: Int? {
didSet {
weightLabel.text = "\(newWeight!) lbs"
}
}
var newSetOne: Int? {
didSet {
setOneLabel.text = "Set 1: \(newSetOne!) reps"
}
}
var newSetTwo: Int? {
didSet {
setTwoLabel.text = "Set 2: \(newSetTwo!) reps"
}
}
var workout: Workout?
// MARK: UITextFieldDelegate
func textFieldDidBeginEditing(textField: UITextField) {
let datePicker = UIDatePicker()
textField.inputView = datePicker
datePicker.addTarget(self, action: #selector(RecordWorkoutTableViewController.datePickerChanged(_:)), forControlEvents: .ValueChanged)
}
func datePickerChanged(sender: UIDatePicker) {
newDate = sender.date
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
// disable editing of date text. datepicker input only
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
return false
}
// MARK: Helper Functions
func closeKeyboard() {
self.view.endEditing(true)
}
// MARK: Touch Events
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
closeKeyboard()
}
override func viewDidLoad() {
super.viewDidLoad()
dateTextField.delegate = self
newDate = NSDate()
if let lastWorkout = workout {
newWeight = lastWorkout.sets[0].weight
newSetOne = lastWorkout.sets[0].repCount
newSetTwo = lastWorkout.sets[1].repCount
} else {
newWeight = 0
newSetOne = 9
newSetTwo = 8
}
weightStepper.stepValue = 5
weightStepper.maximumValue = 995
weightStepper.value = Double(newWeight!)
setOneStepper.stepValue = 1
setOneStepper.maximumValue = 20
setOneStepper.value = Double(newSetOne!)
setTwoStepper.stepValue = 1
setTwoStepper.maximumValue = 20
setTwoStepper.value = Double(newSetTwo!)
}
#IBAction func weightStepperChanged(sender: UIStepper) {
newWeight = Int(sender.value)
closeKeyboard()
}
#IBAction func setOneStepperChanged(sender: UIStepper) {
newSetOne = Int(sender.value)
closeKeyboard()
}
#IBAction func setTwoStepperChanged(sender: UIStepper) {
newSetTwo = Int(sender.value)
closeKeyboard()
}
}
You said in the comments that you have another class in your app named Set. Since this class is in the same module as your table view controller, Swift is prioritizing it over it's built in class.
You can fix this by either renaming your Set class, or explicitly specifying the Swift module in the function declaration:
override func touchesBegan(touches: Swift.Set<UITouch>, withEvent event: UIEvent?) {
closeKeyboard()
}

iOS Swift delegates

I'm very new to Swift, and I'm having trouble using delegates. When the user taps on a table row in AdminAddCatTableViewController, I want to drop a pin on the map at the user's current location in AdminViewController, and I'm trying to do this using a delegate. Obviously there's something wrong with my code, as the pin does not get dropped.
In AdminAddCatTableViewController, I have
import UIKit
import Firebase
protocol AddCatDelegate: class {
func addPin(sender: AdminAddCatTableViewController)
}
class AdminAddCatTableViewController: UITableViewController {
weak var delegate:AddCatDelegate?
let admin = "secret-number"
let ref = Firebase(url: "firease_url")
#IBOutlet weak var snowballGPSLabel: UILabel!
#IBOutlet weak var smokeyGPSLabel: UILabel!
#IBOutlet weak var shadowGPSLabel: UILabel!
#IBOutlet weak var spotsGPSLabel: UILabel!
#IBOutlet weak var sunnyGPSLabel: UILabel!
var catRefArray: [AnyObject] = []
var coord:String = ""
let shareData = ShareData.sharedInstance
func updateCoord() {
if let bar = self.shareData.someString {
self.coord = bar
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "updateCoord", userInfo: nil, repeats: true)
var catNameArray: [AnyObject] = []
catNameArray.append("Snowball")
catNameArray.append("Smokey")
catNameArray.append("Shadow")
catNameArray.append("Spots")
catNameArray.append("Sunny")
for i in 0...4 {
catRefArray.append(self.ref.childByAppendingPath("admin").childByAppendingPath(self.admin).childByAppendingPath(catNameArray[i] as! String))
}
catRefArray[0].observeEventType(.Value, withBlock: { snapshot in
if let value:String = snapshot.value as? String {
self.snowballGPSLabel.text = value
}
}, withCancelBlock: { error in
print(error.description)
// same for the other rows
})
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if (indexPath.row == 0) {
let ref0 = self.ref.childByAppendingPath("admin").childByAppendingPath(self.admin)
ref0.updateChildValues(["Snowball": self.coord])
delegate?.addPin(self)
}
// same for other rows
}
In AdminViewController, I have
import UIKit
import MapKit
import CoreLocation
class AdminViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
#IBAction func logOutDidTouch(sender: AnyObject) {
performSegueWithIdentifier("adminToLogin", sender: self)
}
#IBOutlet weak var mapView: MKMapView!
var locationManager: CLLocationManager!
var previousLocation : CLLocation!
var latitude = 0.0;
var longitude = 0.0;
//Declare Class Variable
let shareData = ShareData.sharedInstance
override func viewDidLoad() {
super.viewDidLoad()
//On loading the screen the map kit view is shown and the current location is found and is being updated.
locationManager = CLLocationManager()
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.delegate = self;
let status = CLLocationManager.authorizationStatus()
if status == .NotDetermined || status == .Denied || status == .AuthorizedWhenInUse {
locationManager.requestAlwaysAuthorization()
locationManager.requestWhenInUseAuthorization()
}
locationManager.startUpdatingLocation()
locationManager.startUpdatingHeading()
mapView.delegate = self
mapView.showsUserLocation = true
mapView.mapType = MKMapType(rawValue: 0)!
mapView.userTrackingMode = MKUserTrackingMode(rawValue: 2)!
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
mapView.mapType = MKMapType(rawValue: 0)!
}
override func viewWillAppear(animated: Bool) {
//updates the location
locationManager.startUpdatingHeading()
locationManager.startUpdatingLocation()
}
override func viewWillDisappear(animated: Bool) {
locationManager.stopUpdatingHeading()
locationManager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
self.latitude = newLocation.coordinate.latitude
self.longitude = newLocation.coordinate.longitude
self.shareData.someString = "\(self.latitude)" + "," + "\(self.longitude)"
print(self.shareData.someString)
}
}
extension AdminViewController: AddCatDelegate {
func addPin(sender:AdminAddCatTableViewController) {
// drop a pin
self.mapView.delegate = self
let coordinate = mapView.userLocation.coordinate
let dropPin = MKPointAnnotation()
dropPin.coordinate = coordinate
dropPin.title = "Cat"
mapView.addAnnotation(dropPin)
}
}
Well you are never setting the delegate on your AdminAddCatTableViewController, so it is always nil and never called.
Why do you even have an extension of AdminViewController? Just remove the extension and make AdminViewController implement the delegate. To set the delegate implement something like this in your AdminViewController:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
super.prepareForSegue(segue, sender: sender)
if segue.identifier == "YourSegueIdentifier" {
if let vc = segue.destinationViewController as? AdminAddCatTableViewController {
vc.delegate = self
}
}
}