I have tried linking the action to the same button but this stops the button from working altogether. I can get it working using the same code if I create a separate button:
#IBAction func Play(sender: AnyObject) {
SoundPlayer.play()
}
#IBAction func stop(sender: AnyObject) {
SoundPlayer.stop()
}
I also need the audio to loop.
Using Nirav code:
class ViewController: UIViewController {
var SoundPlayer:AVAudioPlayer = AVAudioPlayer()
#IBOutlet var btnPlay: UIButton!
#IBOutlet var btnStop: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
let FileLocation = NSBundle.mainBundle().pathForResource("Aspirin", ofType: ".mp3")
do {
SoundPlayer = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: FileLocation!))
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
try AVAudioSession.sharedInstance().setActive(true)
}
catch {
print(error)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func btnTap(sender: UIButton) {
if (sender == self.btnPlay) {
}
else if (sender == self.btnStop) {
}
}
}
1 - Screenshot of storyboard
You can do that just create IBOutlet of both button like this
#IBOutlet var btnPlay: UIButton!
Now bind this action to both button
#IBaction func btnTap(sender: UIButton) {
if (!sender.selected) {
SoundPlayer.play()
}
else {
SoundPlayer.stop()
}
sender.selected = !sender.selected
}
Hope this will help you
Related
This question already has answers here:
How do i keep UISwitch state when changing ViewControllers?
(3 answers)
Closed 4 years ago.
How can I stop the videobackground when I move to another viewcontroller?
because when I move to another viewcontroller, the video and background music continue to be played, and when I go back to the main page two videos overlap. so I would like the video and the music to stop when I move to another viewcontroller, such as when I move in the viewcontroller for the sign up
import UIKit
import SwiftVideoBackground
import Firebase
import FirebaseAuth
class ViewController: UIViewController {
private let videoBackground = VideoBackground()
#IBOutlet weak var usernameField: UITextField!
#IBOutlet weak var passwordField: UITextField!
#IBOutlet weak var mute_img: UIImageView!
#IBOutlet private var muteSwitch: UISwitch!
#IBAction func `switch`(_ sender: UISwitch) {
if (sender.isOn == true)
{
mute_img.isHidden = false
videoBackground.isMuted = true
}
else
{
mute_img.isHidden = true
videoBackground.isMuted = false
}
let shouldMute = sender.isOn
videoBackground.isMuted = shouldMute
UserDefaults.standard.set(shouldMute, forKey:"isMuted")
}
override func viewDidLoad() {
super.viewDidLoad()
let userDefaults = UserDefaults.standard
let shouldMute = userDefaults.bool(forKey: "isMuted")
videoBackground.play(view: view, videoName: "intro", videoType:
"mp4", isMuted: shouldMute, willLoopVideo : true)
muteSwitch.isOn = shouldMute
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == usernameField {
passwordField.becomeFirstResponder()
} else if textField == passwordField {
textField.resignFirstResponder()
}
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Follow the steps:
1) Make an IBOutlet for the switch
#IBOutlet private var muteSwitch: UISwitch!
Don't forget to connect it to the switch in the storyboard.
2) Read the saved value from UserDefaults ( in viewDidLoad ):
override
func viewDidLoad() {
super.viewDidLoad()
let userDefaults = UserDefaults.standard
let shouldMute = userDefaults.bool(forKey: "isMuted")
videoBackground.play(view: view, videoName: "intro", videoType: "mp4", isMuted: shouldMute, alpha : 0.25, willLoopVideo : true)
muteSwitch.isOn = shouldMute
}
3) Save the switch value to UserDefaults ( in #IBAction func `switch`...) :
#IBAction func `switch`(_ sender: UISwitch) {
let shouldMute = sender.isOn
videoBackground.isMuted = shouldMute
UserDefaults.standard.set(shouldMute, forKey:"isMuted")
}
1. Objective - C Version
#import "ViewController.h"
#interface ViewController ()
#property (strong, nonatomic) IBOutlet UISwitch *bluetoothSwitch;
- (IBAction)saveSwitchState:(id)sender;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:#"SwitchState"])
self.bluetoothSwitch.on = [defaults boolForKey:#"SwitchState"];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)saveSwitchState:(id)sender
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([self.bluetoothSwitch isOn])
[defaults setBool:YES forKey:#"SwitchState"];
else
[defaults setBool:NO forKey:#"SwitchState"];
}
#end
Swift Version
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var textField: UITextField!
#IBOutlet weak var stateSwitch: UISwitch!
#IBAction func buttonClicked(_ sender: Any) {
if stateSwitch.isOn {
textField.text = "The Switch is Off"
stateSwitch.setOn(false, animated:true)
} else {
textField.text = "The Switch is On"
stateSwitch.setOn(true, animated:true)
}
}
override func viewDidLoad() {
super.viewDidLoad()
stateSwitch.addTarget(self, action: #selector(stateChanged), for: UIControlEvents.valueChanged)
}
#objc func stateChanged(switchState: UISwitch) {
if switchState.isOn {
textField.text = "The Switch is On"
} else {
textField.text = "The Switch is Off"
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
override func viewDidLoad() {
super.viewDidLoad()
let userDefaults = UserDefaults.standard
if userDefaults.value(forKey: "isMuted") != nil{
let object = userDefaults.value(forKey: "isMuted") as? NSNumber
yourSwitch.isOn = (object?.boolValue)!
}
}
#IBAction func switchChanged(sender: UISwitch) {
let uDefault = UserDefaults.standard
if sender.isOn {
uDefault.setValue(NSNumber(value: true), forKey:"isMuted")
}
else {
uDefault.setValue(NSNumber(value: false), forKey:"isMuted")
}
}
#IBOutlet weak var allStocksSelected: UIImageView!
#IBOutlet weak var shortStocksSelected: UIImageView!
#IBOutlet weak var longStocksSelected: UIImageView!
#IBOutlet weak var myStocksTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
myStocksTableView.delegate = self
myStocksTableView.dataSource = self
}
override func viewDidAppear(_ animated: Bool) {
self.shortStocksSelected.isHidden = true
self.longStocksSelected.isHidden = true
self.allStocksSelected.isHidden = true
}
#IBAction func allStocksButtonPressed(_ sender: Any) {
print("ALL!")
self.stockTypeChanged(stockType: allStocksSelected)
}
#IBAction func shortStocksButtonPressed(_ sender: Any) {
print("SHORT!")
self.stockTypeChanged(stockType: shortStocksSelected)
}
#IBAction func longStocksButtonPressed(_ sender: Any) {
print("LONG!")
self.longStocksSelected.isHidden = false
self.shortStocksSelected.isHidden = true
self.allStocksSelected.isHidden = true
//stockTypeChanged(stockType: longStocksSelected)
}
#IBAction func addNewStockButtonPressed(_ sender: Any) {
}
#IBAction func signOutButtonPressed(_ sender: Any) {
}
private func stockTypeChanged(stockType: UIImageView) {
let stockTypes: [UIImageView] = [allStocksSelected, shortStocksSelected, longStocksSelected]
for (stock) in stockTypes {
if (stock == stockType) {
stock.isHidden = false
} else {
stock.isHidden = true
}
}
}
As shown from my code above, I am basically just trying to hide and show certain image views when buttons are pressed.
I am 100% sure that all of the buttons actions and IB outlets are properly connected, yet the image views are still not hiding and showing, and I cannot figure out why.
I was running into this same issue. Placing your isHidden code to execute on the main thread should solve the problem.
DispatchQueue.main.sync {
}
I'm doing a QR code scanner quiz app where users must get a score of 10 from doing 10 questions. After a user the 1st qn, the score will plus 1 and it will revert them back to the qr scanner page where they must scan the QR code for the next qn. The problem is the passing of the score data. Is there a way to do it without segue?
This is my qn1controller
import UIKit
class Quiz1Controller: UIViewController {
#IBOutlet var question: UILabel!
#IBOutlet var button1: UIButton!
#IBOutlet var button2: UIButton!
#IBOutlet var button3: UIButton!
#IBOutlet var button4: UIButton!
#IBOutlet var LabelEnd: UILabel!
#IBOutlet var scorelabel: UILabel!
var score = Int()
var CorrectAnswer = String()
override func viewDidLoad() {
super.viewDidLoad()
RandomQuestions()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func RandomQuestions(){
var RandomNumber = arc4random() % 1
RandomNumber += 1
switch(RandomNumber){
case 1:
question.text = "Who is the current Deputy Chairman of People's Association?"
button1.setTitle("Lee Hsien Loong", for: .normal)
button2.setTitle("Chan Chun Sing", for: .normal)
button3.setTitle("Goh Chok Tong", for: .normal)
button4.setTitle("Goh Khen Swee", for: .normal)
CorrectAnswer = "2"
Hide()
break
default:
break
}
}
func Hide(){
LabelEnd.isHidden = true
}
func UnHide(){
LabelEnd.isHidden = false
}
#IBAction func Button1(_ sender: Any) {
UnHide()
if (CorrectAnswer == "1"){
self.performSegue(withIdentifier: "correct", sender: self)
}
else {
LabelEnd.text = "Incorrect Answer! Try again"
}
}
#IBAction func Button2(_ sender: Any) {
UnHide()
if (CorrectAnswer == "2"){
score = score + 1
scorelabel.text = "Score:\(score)"
self.performSegue(withIdentifier: "correct", sender: self)
}
else {
LabelEnd.text = "Incorrect Answer! Try again"
}
}
#IBAction func Button3(_ sender: Any) {
UnHide()
if (CorrectAnswer == "3"){
self.performSegue(withIdentifier: "correct", sender: self)
}
else {
LabelEnd.text = "Incorrect Answer! Try again"
}
}
#IBAction func Button4(_ sender: Any) {
UnHide()
if (CorrectAnswer == "4"){
self.performSegue(withIdentifier: "correct", sender: self)
}
else {
LabelEnd.text = "Incorrect Answer! Try again"
}
}
}
And this is my qn2 controller
import UIKit
class Quiz2Controller: UIViewController {
#IBOutlet var question: UILabel!
#IBOutlet var button1: UIButton!
#IBOutlet var button2: UIButton!
#IBOutlet var button3: UIButton!
#IBOutlet var button4: UIButton!
#IBOutlet var LabelEnd: UILabel!
#IBOutlet var scorelabel: UILabel!
var score = Int()
var CorrectAnswer = String()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
RandomQuestions()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func RandomQuestions(){
var RandomNumber = arc4random() % 1
RandomNumber += 1
switch(RandomNumber){
case 1:
question.text = "Who is the founder of People's Association?"
button1.setTitle("Lee Hsien Loong", for: .normal)
button2.setTitle("Lee Kuan Yew", for: .normal)
button3.setTitle("Goh Chok Tong", for: .normal)
button4.setTitle("Goh Khen Swee", for: .normal)
CorrectAnswer = "1"
Hide()
break
default:
break
}
}
func Hide(){
LabelEnd.isHidden = true
}
func UnHide(){
LabelEnd.isHidden = false
}
#IBAction func Button1(_ sender: Any) {
UnHide()
if (CorrectAnswer == "1"){
score = score + 1
scorelabel.text = "Score:\(score)"
self.performSegue(withIdentifier: "correct", sender: self)
}
else {
LabelEnd.text = "Incorrect Answer! Try again"
}
}
#IBAction func Button2(_ sender: Any) {
UnHide()
if (CorrectAnswer == "2"){
self.performSegue(withIdentifier: "correct", sender: self)
}
else {
LabelEnd.text = "Incorrect Answer! Try again"
}
}
#IBAction func Button3(_ sender: Any) {
UnHide()
if (CorrectAnswer == "3"){
self.performSegue(withIdentifier: "correct", sender: self)
}
else {
LabelEnd.text = "Incorrect Answer! Try again"
}
}
#IBAction func Button4(_ sender: Any) {
UnHide()
if (CorrectAnswer == "4"){
self.performSegue(withIdentifier: "correct", sender: self)
}
else {
LabelEnd.text = "Incorrect Answer! Try again"
}
}
}
Story Board :
Delete Seague and do it like as follow. Assume you want to share NSMutableDictionary.
Just take a variable as type you want to share with viewController.
For Exa. you want to share data with ShareViewController then take a variable like
var Dict_data = NSMutableDictionary()
Now Where you want to navigate, just do like Assume It's your ShareViewController. Remember dont forget to give identifier of ShareViewController into StoryBoard.
let PV = self.storyboard?.instantiateViewController(withIdentifier: "ShareViewController") as! ShareViewController
PV.data = dict_share_date
self.navigationController?.pushViewController(PV, animated: true)
Here dict_share_data is your NSMutableDictionry. You can take any type but remember both side types must same. or you can do type casting.
You can use AppDelegate to share data between multiple Viewcontrollers. You can always save ,update and retrieve data defined in AppDelegate of your App. Here is my previous ans to use it efficiently to use Appdelegate.Do let me know if you need Swift version .
In your AppDelegate define your variable as
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var points : String? // Declare your object
.... other methods
}
//You can access the property to save and retrieve your file. You can save
let app = UIApplication.shared.delegate as! AppDelegate
app.points = "yourString"
Yo can read properties from any viewcontroller as per your requirement as
let app = UIApplication.shared.delegate as! AppDelegate
let points = app.points?
You can also use NSNotificationCenter to share data in multiple viewcontoller. Do let me know if you have queries regrading implementing the same.
If you need to pass data from one viewcontroller to another while navigation you can also use instantiation of viewcontoller using storyboard id as #Jeetendra explains in his ans.
i'm a beginner in swift and i have been using this dismissKeyboard() method but it is not working for the keyboard extension.
#IBAction func donePressed (sender: UIButton) {
dismissKeyboard()
}
can anyone tell me why this doesn't work?
thanks.
EDIT: full code
import UIKit
class KeyboardViewController: UIInputViewController {
var keyboardView: UIView!
#IBOutlet var nextKeyboardButton: UIButton!
override func updateViewConstraints() {
super.updateViewConstraints()
// Add custom view sizing constraints here
}
override func viewDidLoad() {
super.viewDidLoad()
self.loadInterface()
}
func loadInterface() {
var keyboardNib = UINib(nibName: "KeyboardView", bundle: nil)
self.keyboardView = keyboardNib.instantiateWithOwner(self, options: nil)[0] as UIView
view.addSubview(self.keyboardView)
view.backgroundColor = self.keyboardView.backgroundColor
self.nextKeyboardButton.addTarget(self, action: "advanceToNextInputMode", forControlEvents: .TouchUpInside)
self.nextKeyboardButton.addTarget(self, action: "advanceToNextInputMode", forControlEvents: .TouchUpInside)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated
}
override func textWillChange(textInput: UITextInput) {
// The app is about to change the document's contents. Perform any preparation here.
}
override func textDidChange(textInput: UITextInput) {
// The app has just changed the document's contents, the document context has been updated.
}
#IBAction func buttonPressed (sender: UIButton) {
let title = sender.titleForState(.Normal)
var proxy = textDocumentProxy as UITextDocumentProxy
proxy.insertText(title!)
}
#IBAction func spacePressed (sender: UIButton) {
var proxy = textDocumentProxy as UITextDocumentProxy
proxy.insertText(" ")
}
#IBAction func deletePressed (sender: UIButton) {
var proxy = textDocumentProxy as UITextDocumentProxy
proxy.deleteBackward()
}
#IBAction func donePressed (sender: UIButton) {
resignFirstResponder()
}
}
Try like that
self.dismissKeyboard()
Maybe try :
view.endEditing(true)
Dismisses the custom keyboard from the screen.
Swift:
self.dismissKeyboard()
Objective-C:
[self dismissKeyboard];
https://developer.apple.com/documentation/uikit/uiinputviewcontroller/1618196-dismisskeyboard?language=objc
When I move from one view controller to another, the switch on the first controller resets itself and does not retain its state.
How can I make it save its state when come back to it after viewing other controllers? And how do I make it save its state after closing the app. I have looked at the various stackOverflow questions and responses and the apple documentation, but nothing seems to work.
Here is my class for the View Controller that has the switch.
class Days: UIViewController {
#IBOutlet weak var switchButton: UISwitch!
var switchState = true
let switchKey = "switchState"
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func saveSwitchPressed(sender:AnyObject) {
if self.switchButton.on {
self.switchState = true
NSUserDefaults.standardUserDefaults().setBool(self.switchState, forKey: switchKey)
NSUserDefaults.standardUserDefaults().synchronize()
println(NSUserDefaults.standardUserDefaults().boolForKey(switchKey))
} else {
self.switchState = false
NSUserDefaults.standardUserDefaults().setBool(self.switchState, forKey: switchKey)
NSUserDefaults.standardUserDefaults().synchronize()
println(NSUserDefaults.standardUserDefaults().boolForKey(switchKey))
}
}
}
I'm a beginner to Swift and generally Xcode. Thank you in advance for your time and help :)
Xcode 8.3 • Swift 3.1
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var switchButton: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
switchButton.isOn = UserDefaults.standard.bool(forKey: "switchState")
}
#IBAction func saveSwitchPressed(_ sender: UISwitch) {
UserDefaults.standard.set(sender.isOn, forKey: "switchState")
}
}
Since you're syncing the on/off state of the switch you could on viewWillAppear: or viewDidAppear: set the state of the switch to the value stored in NSUserDefaults
Something along the lines of
override func viewWillAppear(animated: Bool) {
self.switchButton.on = NSUserDefaults.standardUserDefaults().boolForKey(switchKey)
}
just after code connect UISwitch to IBoutlet.
class ViewController: UIViewController {
#IBOutlet weak var switchButton: UISwitch!
#objc func switchStateDidChange(_ sender:UISwitch!)
{
if (sender?.isOn == true){
print("on")
}
else {
print("off")
}
UserDefaults.standard.set(sender.isOn, forKey: "switchState")
UserDefaults.standard.synchronize()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(false)
switchButton?.isOn = UserDefaults.standard.bool(forKey: "switchState")
switchButton?.addTarget(self, action: #selector(switchStateDidChange(_:)), for: .touchUpInside)
}
}