Show / Hide DatePicker tapping on a TextField - xcode

I have a profile view, where there are 4 TextField, in one of which must be inserted the date using a DatePicker, I realized, though, that this DatePicker is always visible, on the other hand I would like to appear when you click on the TextField that contains the date. How can I fix?
The code that I inserted is this:
import UIKit
class ProfileViewController: UIViewController {
#IBOutlet weak var bornDate: UITextField!
#IBOutlet weak var dateSec: UIDatePicker!
override func viewDidLoad() {
super.viewDidLoad()
dateSec.addTarget(self, action: Selector("datePickerChanged:"), forControlEvents: UIControlEvents.ValueChanged)
}
func datePickerChanged(datePicker:UIDatePicker) {
var dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
var strDate = dateFormatter.stringFromDate(dateSec.date)
bornDate.text = strDate
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

Ok, I solved the problem with the date format by inserting this piece of code:
var dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd"
let d = NSDate()
let s = dateFormatter.stringFromDate(d)
println(s)

Related

Converting String from a label into Int

I have a button that adds 1 to an a attempt score label and then a button that adds a 1 or 0 to the correct score label depending which button is pressed. This data is then passed to various viewControllers. On the last viewController i want to convert the string from the label into a int and then do a simply calculation in order to get a percentage. The code i have tried is below. The percentage is not being displayed so I do not think i am converting it correctly?
On previous VC the aScore and cScore are set as variable that = 0. For example..
var aScore = 0
var cScore = 0
I am passing the data between VC and then on the final viewController the following code exits.
import UIKit
class gViewController: UIViewController {
#IBOutlet weak var correctScore: UILabel!
#IBOutlet weak var attemptScore: UILabel!
#IBOutlet weak var percentage: UILabel!
var aScore: Int!
var cScore: Int!
var percentage1: Int!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
correctScore.text = NSString(format: "%i", cScore) as String
attemptScore.text = NSString(format: "%i", aScore) as String
let c:Int? = Int(correctScore.text!)
let a:Int? = Int(attemptScore.text!)
percentage1 = c!/a!
percentage.text = NSString(format: "%i", percentage1) as String
}
Try this
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.correctScore.text = String(format: "%.1f", cScore)
self.attemptScore.text = String(format: "%.1f", aScore)
var percentage1 = Float(cScore)/Float(aScore)
self.percentage.text = String(format: "%.1f", percentage1)
}

Expression resolves to an unused function

So I have been messing around with saving and calling from NSUserDefaults and I have made progress but I keep on getting this error.
"Expression resolves to an unused function"
The program is supposed to save a string from a textfield so that if you close the program and open it the string will still be their. Unless, you press save again and then the string (Label) will change.
The problem prevents me from running the program so I have not been able to test the new code that I wrote.
Here is the source code feel free to try it. All of this is written in swift.
//
// ViewController.swift
// Help
//
// Created by Lucas on 9/30/15.
// Copyright (c) 2015 Lucas. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
#IBOutlet var Savedlbl: UILabel!
#IBOutlet var Textfield: UITextField!
#IBOutlet var Label: UILabel!
var current = ""
var Saved = ""
override func viewDidLoad() {
super.viewDidLoad()
let currentDefault = NSUserDefaults.standardUserDefaults()
Savedlbl.text = currentDefault.valueForKey("saved") as? String
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func Set(sender: AnyObject) {
setall()
}
func setall()
{
current = Textfield.text!
Label.text = Textfield.text!
Savedlbl.text = Textfield.text!
let currentDefault = NSUserDefaults.standardUserDefaults()
Savedlbl.text = currentDefault.valueForKey("saved") as? String
currentDefault.setValue(Saved, forKey: "saved")
currentDefault.synchronize
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The line:
currentDefault.synchronize
should be:
currentDefault.synchronize()

Class has no initializers (Xcode 6.3)

Trying to figure out errors after updating to Xcode 6.3. I have a class thats getting the error 'Class has no initializers' could anyone tell me how to fix this?
class TodayViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, BWWalkthroughViewControllerDelegate {
var events: [EKEvent] = []
let eventStore = EKEventStore()
var pttCalendar: EKCalendar?
let walkthroughVC : BWWalkthroughViewController?
#IBOutlet weak var tableView: UITableView!
var dateFormatter = NSDateFormatter()
override func viewDidLoad() {
super.viewDidLoad()
requestCalendarAccess()
let firstLaunch = NSUserDefaults.standardUserDefaults().boolForKey("FirstLaunch")
if firstLaunch {
println("Not first launch.")
}
else {
showWalkthrough()
println("First launch, setting NSUserDefault.")
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "FirstLaunch")
}
self.tableView.rowHeight = 50
dateFormatter.dateFormat = "EE, MMM dd"
let dateForLabel = dateFormatter.stringFromDate(NSDate())
self.title = dateForLabel
}
You forgot the override func init()
You need an initialiser to set the value
let walkthroughVC : BWWalkthroughViewController?
Setting that as a var will remove the error. It will of course default to nil.

Swift error : class RecordSoundsViewController has no initializers

class RecordSoundsViewController: UIViewController, AVAudioRecorderDelegate{
#IBOutlet weak var recordButton: UIButton!
#IBOutlet weak var recodinginProgress: UILabel!
#IBOutlet weak var stopButton: UIButton!
var audioPlayer: AVAudioPlayer!
var recordAudio: RecordedAudio!
var audioRecorder:AVAudioRecorder
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.
}
override func viewWillAppear(animated: Bool) {
//hide the stop button
stopButton.hidden = true
recordButton.enabled = true
}
#IBAction func recordAudio(sender: UIButton) {
recordButton.enabled = false
stopButton.hidden = false
recodinginProgress.hidden = false
//TODO: Record the user"s voice
let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,
.UserDomainMask, true)[0] as String
let currentDateTime = NSDate()
let formatter = NSDateFormatter()
formatter.dateFormat = "ddMMyyyy-HHmmss"
let recordingName = formatter.stringFromDate(currentDateTime)+".wav"
let pathArray = [dirPath, recordingName]
let filePath = NSURL.fileURLWithPathComponents(pathArray)
println(filePath)
var session = AVAudioSession.sharedInstance()
session.setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil)
audioRecorder = AVAudioRecorder(URL: filePath, settings: nil, error: nil)
audioRecorder.delegate = self
audioRecorder.meteringEnabled = true
audioRecorder.prepareToRecord()
audioRecorder.record()
}
I don't know what I am doing wrong. My error is coming on my class.
It says
class RecordSoundsViewController has no initializers on RecordSoundsViewController: UIViewController, AVAudioRecorderDelegate{
The error message is a bit bad from the compiler. The reason you see the error is because you have a property which does not have a default value.
In Swift all values needs to have a default value unless it's an optional.
In your case it's this property: var audioRecorder:AVAudioRecorder
In your case I would make this property an optional: var audioRecorder:AVAudioRecorder? and make sure to check for nil when using. Or to make it an implicitly unwrapped optional (if you know there's always gonna be a value): var audioRecorder:AVAudioRecorder!

Updates Labels in Swift when using popoverController

I have a question about swift,
I made a popover controller in a UIViewController,which display a list of books
and when the user click on one of the books, the label on the viewController should be updated with the name of the selected book.
But in my case when I select a name of a book, the label does not update
here is the code :
// View Controller
import UIKit
class ViewController: UIViewController,UIPopoverControllerDelegate {
var popoverController : UIPopoverController? = nil
#IBOutlet var bookName : UILabel
var BookNameString : String?{
didSet{
configureView()
}
}
func configureView() {
// Update the user interface for the detail item.
if let detail = self.BookNameString {
if let label = bookName {
label.text = detail
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func Click(sender : UIButton) {
var tableView:TableViewController = TableViewController(style: UITableViewStyle.Plain)
var popoverContent:UINavigationController = UINavigationController(rootViewController: tableView)
self.popoverController = UIPopoverController(contentViewController: popoverContent)
self.popoverController!.delegate = self
self.popoverController!.presentPopoverFromRect(sender.frame, inView: self.view, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
and here is the code of the TableViewController when a row is selected:
// TableViewController
override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!){
var storyboard = UIStoryboard(name: "Main", bundle: nil)
var details = storyboard.instantiateViewControllerWithIdentifier("ViewController") as ViewController
var keyString = bookSectionKeys[indexPath.section]
var bookValues = book.booksLetters[keyString]!
var selectedBookString = bookValues[indexPath.row]
var selectedBookValues = book.bookDictionary[selectedBookString]!
details.BookNameString = selectedBookString
}
I was able to solve this problem a few weeks ago and I want to share the solution with you :)
I solve it using protocols.
OK Here what I did in details:
First I created a protocol in the view that I want it to display inside the popover and I named the protocol "DismissPopoverDelegate"
protocol DismissPopoverDelegate{
func didSelectBook(SelectedBook:String)
}
Then I declared a variable of type DismissPopoverDelegate and name it "delegate"
var delegate: DismissPopoverDelegate?
Then in the didSelectRowAtIndexMethod:
override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!){
var keyString = bookSectionKeys[indexPath.section]
var bookValues = book.booksLetters[keyString]!
var selectedBookString = bookValues[indexPath.row]
delegate?.didSelectBook(selectedBookString)
}
After that inside the View that contains the popover (View Controller), I set the delegate of the view:
class ViewController: UIViewController, DismissPopOverDelegate, UIPopoverControllerDelegate{
Then to make the view confirm to the protocol DismissPopOverDelegate, I implement the method "didSelectBook" Inside the view:
func didSelectBook(SelectedBook:String){
popoverController!.dismissPopoverAnimated(true) // This is Optional
bookName.text = SelectedBook // Make the label text equal to the selected book From the table
}
Finally, I set the delegate to the tableView to View Controller
tableView.delegate = self
That's it :)
Here is the full code of the viewController that contains the popover
import UIKit
class ViewController: UIViewController, DismissPopOverDelegate, UIPopoverControllerDelegate{
#IBOutlet var booksbarButton : UIBarButtonItem
#IBOutlet var bookName : UILabel
var popoverController : UIPopoverController? = nil
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func showTableView(sender : UIBarButtonItem) {
var tableView:TableViewController = TableViewController(style: UITableViewStyle.Plain)
tableView.delegate = self
var popoverContent:UINavigationController = UINavigationController(rootViewController: tableView)
self.popoverController = UIPopoverController(contentViewController: popoverContent)
popoverController!.delegate = self
self.popoverController!.presentPopoverFromBarButtonItem(booksbarButton, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true)
}
func didSelectBook(SelectedBook:String){
popoverController!.dismissPopoverAnimated(true)
bookName.text = SelectedBook
}
}

Resources