Multiple UISwitches To Turn On/Off - uiswitch

I am new to swift and attempting to place 5 UISwitches on one View Controller. I would like each one to turn the other 4 (or other 1) switches off. I am having a pretty rough go of figuring this one out.. Each one I have named with a label of switch1, switch2, etc. through 5. However, when i type switch1 into the ViewController.swift the variable is not recognized. I assumed I'd be able to type switch1.enabled = false or something to that effect but I only get an error indicating switch1 is not recognized. Help!

You are doing wrong, if you want use switch in controller you must create outlet in view controller.
e.g.
class SwitchDemo: UIViewController{
#IBOutlet weak var switch1: UISwitch!
#IBOutlet weak var switch2: UISwitch!
#IBOutlet weak var switch3: UISwitch!
#IBOutlet weak var switch4: UISwitch!
#IBOutlet weak var switch5: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
}
// Create Switch Toggle Action
#IBAction func onClickSwitch1(_ sender: Any) {
if self.contactSwitch.isOn {
self.switch2.isOn = false
self.switch3.isOn = false
self.switch4.isOn = false
self.switch5.isOn = false
}else {
}
}
}

Related

I can't use instance member array within property initializer

import UIKit
class ViewController: UIViewController {
#IBOutlet var Text1: UITextField!
#IBOutlet var Text2: UITextField!
#IBOutlet var Text3: UITextField!
#IBOutlet var Label: UILabel!
let array = ["Frodo", "sam", "wise", "gamgee"]
let randomIndex = Int(arc4random_uniform(UInt32(array.count))) //Problem is here
#IBAction func button(_ sender: Any) {
Label.text = array[randomIndex]
}
}
You didn't ask any question so I assume you have problem with accessing count of array.
In general you can't access any of instance members until init is completed.
There are (at least) three solutions for your problem.
First is to override all init required by UIViewController and set randomIndex there.
Second is to use lazy for randomIndex:
lazy var randomIndex = {
Int(arc4random_uniform(UInt32(array.count)))
}()
Third is to use some model (class/struct) for those data and inject it to ViewController
You cannot run the line to get the random index on the top level of the class.
It must be located within a function / method:
#IBAction func button(_ sender: Any) {
let randomIndex = Int(arc4random_uniform(UInt32(array.count)))
Label.text = array[randomIndex]
}
And please conform to the naming convention that variable names start with a lowercase letter (text1, label).

Passing a value from inputField to NSTextField

I'd like to pass string value from one NSTextField to another NSTextField pressing a button. I used for this for-in loop. I need to pass a value from inputField to visibleText1, then to visibleText2 and then to visibleText3. But it doesn't work.
import Cocoa
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
#IBOutlet weak var window: NSWindow!
#IBOutlet weak var inputField: NSTextField!
#IBOutlet weak var visibleText1: NSTextField!
#IBOutlet weak var visibleText2: NSTextField!
#IBOutlet weak var visibleText3: NSTextField!
func applicationDidFinishLaunching(aNotification: NSNotification) { }
func applicationWillTerminate(aNotification: NSNotification) { }
#IBAction func applyButton(sender: AnyObject) {
for u in (visibleText1.stringValue...visibleText3.stringValue) {
visibleText.stringValue[u] = inputField.stringValue
inputField.stringValue = ""
}
}
}
Xcode gives me an error:
// Type 'ClosedInterval<String>' does not conform to protocol 'SequenceType'
How how to do it right?
No you can't do that because you can't create a range of string values of different text fields.
You could make an array of the three fields and enumerate that:
#IBAction func applyButton(sender: AnyObject) {
for field in [visibleText1, visibleText2, visibleText3] {
field.stringValue = inputField.stringValue
}
inputField.stringValue = ""
}
or with the forEach function
#IBAction func applyButton(sender: AnyObject) {
[visibleText1, visibleText2, visibleText3].forEach {
$0.stringValue = inputField.stringValue
}
inputField.stringValue = ""
}
Resetting the inputField in the repeat loop would always apply an empty string after the first iteration.
There are several things wrong with this, but I will start with what will work:
import Cocoa
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
#IBOutlet weak var window: NSWindow!
#IBOutlet weak var inputField: NSTextField!
#IBOutlet weak var visibleText1: NSTextField!
#IBOutlet weak var visibleText2: NSTextField!
#IBOutlet weak var visibleText3: NSTextField!
func applicationDidFinishLaunching(aNotification: NSNotification) { }
func applicationWillTerminate(aNotification: NSNotification) { }
#IBAction func applyButton(sender: AnyObject) {
for u in [visibleText1, visibleText2, visibleText3] {
u.stringValue = inputField.stringValue
}
}
}
So what's wrong with the original?
1) Your (visibleText1.stringValue...visibleText3.stringValue) is of type String ... String, which is not what you intended. You need to have an array of NSTextFields.
2) visibleText.stringValue[u] is not even a thing. There is no variable visibleString, and even if it was an NSTextField - which I think is what you want it to be, it's .stringValue is a String, and not an array.
3) What are you doing setting inputField.stringValue = "" inside the for loop? If your construct worked, only the first field would be set.
4) Not an error, but why are you doing all of this inside NSApplicationDelegate, rather than a viewController?

Cannot pass UIImageView between view controllers using a push segue

I'm trying to pass a UIImageView from a Master View Controller to a Detailed View Controller using a Push Segue. Everything loads fine on the Master View Controller, and I've created a push segue using the UIImageView on the Master View Controller. Here's my Master View Controller -
class TrackMasterViewController: UIViewController {
#IBOutlet weak var artistName: UILabel!
#IBOutlet weak var albumName: UILabel!
#IBOutlet weak var numberOfTracks: UILabel!
#IBOutlet weak var coverImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let firstRandomNumber = calculateRandomNumber()
artistName.text = Track(index: firstRandomNumber).artist
albumName.text = Track(index: firstRandomNumber).album
coverImage.image = Track(index: firstRandomNumber).image
numberOfTracks.text = Track(index: firstRandomNumber).track
}
It's the coverimage which is being passed. Here's my segue function -
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "trackSegue" {
let playlistDetailController = segue.destinationViewController as? TrackDetailViewController
playlistDetailController?.image = UIImage(named: coverImage)
}
}
And in my Detailed View Controller, i have the following:
class TrackDetailViewController: UIViewController {
#IBOutlet weak var albumCover: UIImageView!
var image:UIImage? = nil
override func viewDidLoad() {
super.viewDidLoad()
albumCover.image = image
// Do any additional setup after loading the view.
}
}
Any help determining what the issue is would be greatly appreciated.
Try changing inside your prepareForSegue:, instead of using:
playlistDetailController?.image = UIImage(named: coverImage)
Use:
playlistDetailController.image = coverImage.image
Good luck!

develop mac app swipe from one ViewController to another with Swift(not use storyboard)

i'm the new one develop mac app.When i want to do what i say in title,presentViewController method but with an error said i pass the wrong parameter,but what pass is total the same as what it want.
The error message said "Cannot invoke 'presentViewController' with an argument list of type..."
import Cocoa
class MainViewController: NSViewController {
var uploadViewController: UploadViewController!
#IBOutlet weak var HostFileList: NSScrollView!
#IBOutlet weak var AddFileToHost: NSButton!
#IBOutlet weak var DeleteFileFromHost: NSButton!
#IBOutlet weak var Host: NSTextField!
#IBOutlet weak var Port: NSTextField!
#IBOutlet weak var ConnectServer: NSButton!
#IBOutlet weak var UploadFile: NSButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
}
extension MainViewController {
#IBAction func UploadFile(sender: AnyObject) {
var uploadViewController = UploadViewController(nibName: "MasterViewController", bundle: nil)
self.presentViewController(uploadViewController, animator: NSTableViewAnimationOptions.SlideRight)
}
}
On OSX, there is no UINavigationController doing the push/pop stuff and the animation for you!
So you have to do it yourself using ViewAnimations and removeFromSuperview and addSubview to switch out the views manually.
there also a lot of ready made ways for you to do iOS-like stuff on the mac: https://www.google.de/search?client=safari&rls=en&q=uinavigationcontroller+osx&ie=UTF-8&oe=UTF-8&gfe_rd=cr&ei=T3OjVfeqPNfIgATS64G4Dw
The most lightweight at first glance looks to be:
https://github.com/bfolder/BFNavigationController
(note: Im not the author and I dont even know him! :D)

Changing image of UIButton via click - XCode 6 Swift

Im simply trying to make it so when I click on a UIButton (for which it currently shows the image of a shell), the image changes into something else (in this case, a coin).
This is what i tried so far and have not had any success. I cant find anything to do this for Swift.Thanks.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var lblOutput: UILabel!
#IBOutlet weak var lblWin: UILabel!
#IBOutlet weak var lblLost: UILabel!
#IBOutlet weak var lblWinsAmt: UILabel!
#IBOutlet weak var lblLossesAmt: UILabel!
let coin = UIImage(named: "penny_head") as UIImage;
override func viewDidLoad() {
super.viewDidLoad()
//imgShell1.hidden = true //doesnt work
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func btnStart(sender: UIButton) {
}
#IBAction func btnShell1(sender: UIButton) {
sender.setImage(coin,forState: UIControlState.Highlighted);
}
The way you're setting up the control is incorrect. Assuming you have a button property named btnShell (and it's the button you want to setup) change your viewDidLoad() method to:
override func viewDidLoad()
{
super.viewDidLoad()
btnShell.setImage(imgShell1, forState:.Normal);
btnShell.setImage(coin, forState:.Highlighted);
}
And then remove the setImage(_:forState:) call from the action method:
#IBAction func btnShell1(sender: UIButton) {
sender.setImage(coin,forState: UIControlState.Highlighted);
}
To permanently change the button image on tap, you have to use the .Normal enum case and not .Highlighted for the control state:
sender.setImage(coin,forState: UIControlState.Normal)
Setting the image for the .Highlighted state makes the new image appear only when the button is in that state, i.e. when it is tapped.
If you are looking to change the UIButton's background image permanently you have to use Antonio's method:
sender.setImage(coin,forState: UIControlState.Normal)
This won't change the UIKit's default highlighting when you tap the button. When you don't want the button to be highlighted when you touch it or have different appearances for different states, then you might be better off using an UIImageView.
In viewDidLoad():
imgView?.image = imgOne
imgView?.userInteractionEnabled = true
imgView?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "changeImage:"))
The function that changes the image:
func changeImage(recognizer: UITapGestureRecognizer){
self.imgView?.image = imgTwo
}
You can also use isSelected.
button.setImage(image2, for: .normal)
button.setImage(image1, for: .selected)

Resources