Xcode - control drag function not working - xcode

Beneath is my code,
Currently, it isn't working and allowing me to connect a button to my swift file (main storyboard). Also, the timer function isn't working, would this be to do with the function not working as well?
unsure on how to fix this, let me know if you need any other screen shots.
Any help will be appreciated.
Thanks
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var CounterLabel: UILabel!
var time = 30
var timer = Timer()
#IBAction func start(_ sender: UIButton)
{
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.action), userInfo: nil, repeats: true)
}
func action()
{
time += 1
}
//GIFS
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.
}
}

Related

Use of unresolved identifier 'self'

I am working on a Mac OS X application with Swift.
This is my first time and I thought it would be the same as it is on iOS.
So I got this error (in the title) on this code:
import Cocoa
import AppKit
class LoginViewController: NSViewController {
#IBOutlet weak var emailTextField: NSTextField!
#IBOutlet weak var passwordTextField: NSSecureTextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear() {
}
super.viewDidAppear()
if NSUserDefaults.standardUserDefaults().valueForKey("uid") != nil && CURRENT_USER!.authData != nil
{
self.logoutButton.hidden = false
}
}
func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
func loginAction(sender: AnyObject)
{
let email = self.emailTextField.text
let password = self.passwordTextField.text
...
}
}
What do I have to write instead of self?
Using self is correct. Try using the property stringValue instead of text.
Here is the code that worked for me:
#IBOutlet weak var emailTextField: NSTextField!
#IBAction func sendTapped(sender: AnyObject) {
let email = self.emailTextField.stringValue
print(email)
}

Issues with NSNotificationCenter in #IBAction function

I am working on an app that requires my main view controller to receive notifications from its child view controller. To do this, I set up the observer in the viewDidLoad() method of the parent controller, and I am trying to call the postNotificationName() function when a button is pressed that is located in the child view controller.
When the postNotificationName() call is located in the #IBAction func buttonPressed(){ } function, the observer never gets the notification. However, when the same code is called from a different function in the same view controller, it works.
I thought this might be a thread issue, and unsuccessfully tried many of the solutions for that issue. I'm not very familiar with threading, though, so maybe I still missed it. Does anyone have any idea what the issue might be?
Thanks for the help!
ViewController
class GameController: UIViewController {
override func viewDidLoad() {
super.init()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "attemptHumanMove:", name: Constants.NSNotificationKey.tilePressed, object: nil)
}
func attemptHumanMove(notification: NSNotification) {
print("test")
}
ChildViewController
#IBAction func tileTouched(sender: AnyObject) {
NSNotificationCenter.defaultCenter().postNotificationName(Constants.NSNotificationKey.tilePressed, object: nil, userInfo: ["a": 0])
}
Experimenting with the flow you have mentioned, the following code does receive the notification message from a child view controller.
ParentViewController
class ViewController: UIViewController {
#IBOutlet weak var notificationMsgLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
notificationMsgLabel.text = "Waiting for notification..."
NSNotificationCenter.defaultCenter().addObserver(self, selector: "attemptHumanMove:", name: "tilePressed", object: nil)
}
func attemptHumanMove(notification: NSNotification) {
print("Notification message received!")
notificationMsgLabel.text = "Notification received!!!"
}
}
ChildViewController
class ChildViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func sendNotification() {
print("Sending notification message!!!")
NSNotificationCenter.defaultCenter().postNotificationName("tilePressed", object: nil, userInfo: ["a": 0])
}
}
Here you can find the screen shot of the storyboard:
Storyboard Snapshot

How to update label in Second ViewController with information from First ViewController every second

I have an app that has two ViewControllers. On the first there is a count of current speed in realtime through CLLocationManager. Also there is a label that shows current speed with update by timer (NSTimer). In second ViewController there is another Label, where this current speed has to be shown too. It shows it, but don't update. I tried to set second timer (different ways: in first VC, in second VC - there is always was an error or just nothing).
Will be grateful for help, thanks!
First VC
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
#IBOutlet weak var mapView: MKMapView!
#IBOutlet weak var currentSpeedLabel: UILabel!
var manager = CLLocationManager()
var currentSpeed: CLLocationSpeed = CLLocationSpeed()
var timer = NSTimer()
override func viewDidLoad() {
super.viewDidLoad()
mapView.mapType = MKMapType.Hybrid
trackingMe()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func HUDMapView(sender: AnyObject) {
speedCount()
}
#IBAction func findMe(sender: AnyObject) {
trackingMe()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation: CLLocation = locations[0] as CLLocation
manager.stopUpdatingLocation()
let location = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude)
let span = MKCoordinateSpanMake(0.05, 0.05)
let region = MKCoordinateRegion(center: location, span: span)
mapView.setRegion(region, animated: true)
}
func trackingMe() {
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
mapView.showsUserLocation = true
currentSpeedUpdate()
}
func currentSpeedUpdate() {
timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: Selector("speedCount"), userInfo: nil, repeats: true)
}
func speedCount() {
currentSpeed = manager.location!.speed
currentSpeedLabel.text = String(format: "%.0f km/h", currentSpeed * 3.6)
}
override func prepareForSegue(segue: (UIStoryboardSegue!), sender: AnyObject!) {
let speedController = segue.destinationViewController as! speedViewController
currentSpeed = manager.location!.speed
speedController.showSpeed = currentSpeedLabel.text
}
}
Second VC
import UIKit
class speedViewController: UIViewController {
#IBOutlet weak var secondSpeedLabel: UILabel!
var showSpeed: String!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
secondSpeedLabel.text = showSpeed
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func back(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
Project Link
You could use a Singleton to hold the LocationManager. Then you can access it from all over your app. When you move to a second VC you can either change the delegate to the second VC or just get the needed data manually.
Remember that a delegate can only point to one "receiver". Changing the delegate will stop updates in the first VC. but since it is now a Singleton you can also store information in there about past locations / speeds. When dismissing the second VC get the stored data and update.
This will keep running until you call stop()
The code was simplified a bit to illustrate the idea.
VC Code:
import UIKit
import CoreLocation
class ViewController: UIViewController, TrackerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
Tracker.shared.delegate = self
Tracker.shared.start()
}
func speedUpdate(speed: CLLocationSpeed) {
print(speed)
}
}
Singleton Code:
import UIKit
import MapKit
import CoreLocation
class Tracker: NSObject, CLLocationManagerDelegate {
static var shared = Tracker()
private var manager = CLLocationManager()
private var timer = NSTimer()
var region : MKCoordinateRegion?
var currentSpeed: CLLocationSpeed = CLLocationSpeed()
weak var delegate : TrackerDelegate?
private override init() {
super.init()
manager.delegate = self
manager.requestWhenInUseAuthorization()
}
internal func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
manager.stopUpdatingLocation()
let userLocation: CLLocation = locations[0] as CLLocation
let coordinates2D = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude)
let span = MKCoordinateSpanMake(0.05, 0.05)
region = MKCoordinateRegion(center: coordinates2D, span: span)
currentSpeed = userLocation.speed
guard let del = delegate else {
return
}
del.speedUpdate(currentSpeed)
}
func start() {
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.startUpdatingLocation()
timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: Selector("loopUpdate"), userInfo: nil, repeats: true)
}
func stop() {
timer.invalidate()
}
internal func loopUpdate() {
// restart updating
manager.startUpdatingLocation()
}
}
Delegate for the Singleton:
Add more functions, or more values to the current function to get more feedback.
protocol TrackerDelegate : class {
func speedUpdate(speed:CLLocationSpeed)
}

What function do I use to call out the complete menu in CVCalendar?

I am trying to call the entire menu with Month title from Mozharovsky/CVCalendar but I'm not sure what function will call this out?
This is the current code I am using:
import UIKit
import CVCalendar
class ViewController: UIViewController, CVCalendarViewDelegate, CVCalendarMenuViewDelegate {
#IBOutlet weak var calendarView: CVCalendarView!
#IBOutlet weak var menuView: CVCalendarMenuView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationController?.navigationBar
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
calendarView.commitCalendarViewUpdate()
menuView.commitMenuViewUpdate()
}
func presentationMode() -> CalendarMode {
return CalendarMode.MonthView
}
func firstWeekday() -> Weekday {
return Weekday.Sunday
}
}
This is the what is rendered when compiled:
If you want to see the month title also you need to create a UIlabel and UIlabel outlet as such:
#IBOutlet weak var monthLabel: UILabel!
I got this answer by copying the code from Mozharovsky/CVCalendar Demo ViewController.swift file

iOS 8 Swift: Cannot unhide/hide UIView on button click

This is driving me crazy. I am trying to un-hide a hidden UIView on button click but its not working. Here is the code
import UIKit
class DownloadViewController: UIViewController {
#IBOutlet var activityView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.activityView.hidden = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func downloadAction(sender: AnyObject) {
self.activityView.hidden = false
}
}
Please help me. This is driving me nuts, that its not doing such a simple thing.
Make sure that your outlet is connected to the correct button in Interface Builder, try connecting it again by ctrl-dragging from the button in IB to the #IBOutlet code.
This code works, are you getting an error or does the button not do anything?
Swift 3
import UIKit
class DownloadViewController: UIViewController {
#IBOutlet var activityView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.activityView.isHidden = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func downloadAction(sender: AnyObject) {
self.activityView.isHidden = false
}
}

Resources