Cannot pass UIImageView between view controllers using a push segue - uiimageview

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!

Related

Multiple UISwitches To Turn On/Off

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 {
}
}
}

How to access variable from one class in another? Swift Code

I am having an issue getting one simple variable from one class to another and it is beyond extremely frustrating :/...
Here is the deal I have two view controller classes named: ViewController.swift and ViewController2.swift
ViewController.swift is linked to a storyboard that has sort of an inventory bag that I have placed which is just an image. Then there is an #IBAction for when you click on the bag it opens up and the second storyboard pops into view. This is controlled by ViewController2.swift. All I am looking to do is simply pass the center of the bag image from ViewController to ViewController2 but I can't seem to get it to work any help would be greatly appreciated.
class ViewController: UIViewController {
#IBOutlet weak var InventoryBag: UIImageView!
var bagCenter:CGPoint = CGPoint(x: 0, y: 0)
override func viewDidLoad() {
super.viewDidLoad()
#IBAction func InventoryButtonTapped(sender: UIButton) {
self.InventoryBag.image = UIImage(named: "backpackimageopen")
bagCenter = self.InventoryBag.center
func transferViewControllerVariables() -> (CGPoint){
return bagCenter
}
When I print the bagCenter from this ViewController it works properly and gives me a correct value. So the bagCenter variable I would like to somehow pass over to ViewController2.swift.
Here is what I tried from ViewController2.swift but it never seems to work and always gives me a 0 rather than the actual value.
class ViewController2: UIViewController {
#IBOutlet weak var HideButton: UIButton!
#IBOutlet weak var InventoryCollection: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//Load the center of the inventory bag to this view controller to align the hide button.
var bagCenter = ViewController().transferViewControllerVariables()
}
But when I do this it always results in a 0 and I don't get the actual coords of the bag that are showing up in ViewController1.
Create a following variable in ViewController2
var previousViewController: ViewController!
Add following line of code in your ViewController Class
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){
if segue.destinationViewController .isKindOfClass(ViewController2){
let vc2 = segue.destinationViewController as! ViewController2
vc2.previousViewController = self
}
}
Now in viewDidLoad method of ViewController2 you can access bagCenter like below:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
var bagCenter = previousViewController.transferViewControllerVariables()
}
Try this in view Controller
class ViewController: UIViewController {
#IBOutlet weak var InventoryBag: UIImageView!
var bagCenter:CGPoint = CGPoint(x: 0, y: 0)
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func InventoryButtonTapped(sender: AnyObject) {
self.InventoryBag.image = UIImage(named:"MAKEUP_SHARE.jpg")
bagCenter = self.InventoryBag.center
performSegueWithIdentifier("Go", sender: self)
}
// Give a segue identifier in storyboard
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "yoursegueidentifier" {
let dvc = segue.destinationViewController as? ViewController2
dvc!.bagCenter = bagCenter
}
}
}
and in view controller2
class ViewController2: UIViewController {
var bagCenter:CGPoint!
override func viewDidLoad() {
super.viewDidLoad()
print(bagCenter)
}
}

iterate through objects/variables Swift

How can I iterate through objects/variables in Swift. Can I create an array or dictionary when I have objects attached so that I don't have to write code for each button. I'm a nubie so please speak to me like I'm four. Thanks for the help in advance.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var button1: UIButton!
#IBOutlet weak var button2: UIButton!
#IBOutlet weak var button3: UIButton!
...
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.button1.alpha = 0.0
self.button2.alpha = 0.0
self.button3.alpha = 0.0
...
}
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var button1: UIButton!
#IBOutlet weak var button2: UIButton!
#IBOutlet weak var button3: UIButton!
var arrayOfButtons = [UIButton]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
arrayOfButtons = [button1, button2, button3]
for button in arrayOfButtons {
button.alpha = 0.0
}
}
In addition to Tim's answer, you can also create buttons programmatically, and deal with them in your code!
override func viewDidLoad() {
for i in 1...10 {
let button = UIButton()
button.frame = CGRectMake((CGFloat(i-1)*50), 0, 50, 50)
button.targetForAction("buttonClick:", withSender: self)
button.tag = i
self.view.addSubview(button)
}
}
func buttonClick(sender:AnyObject) {
let tag = sender.tag!
//click logic here
}

sending data to viewcontroller shows nil data

for some reason i cannot get the Value to send to my AddParticipant View.
Here's the Data before "ValuetoPass" and after the segue:"LAbelText"
ValuetoPass = GXEuoAkhjP
LabelText =
TableView Code for segue:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//CODE TO BE RUN ON CELL TOUCH
let indexPath = tableView.indexPathForSelectedRow!;
let currentCell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell!;
let valueToPass = self.participantId[indexPath.row] as String
print("ValuetoPass = ",valueToPass)
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "editParticipant") {
let viewController = segue.destinationViewController as! AddViewController
viewController.LabelText = valueToPass; }
}
}
Code for AddViewController:
#IBOutlet weak var firstnameTF: UITextField!
#IBOutlet weak var lastnameTF: UITextField!
#IBOutlet weak var gradeTF: UITextField!
#IBOutlet weak var teacherTF: UITextField!
#IBOutlet weak var emailTF: UITextField!
#IBOutlet weak var phoneTF: UITextField!
#IBOutlet weak var transportationTF: UITextField!
#IBOutlet weak var userSchoolTF: UITextField!
var LabelText = String()
#IBOutlet weak var qrCode: UIImageView!
#IBOutlet weak var userPicture: UIImageView!
override func viewDidAppear(animated: Bool) {
}
override func viewDidLoad() {
super.viewDidLoad()
print("LabelText = ", LabelText)
let currentUser = PFUser.currentUser()
currentUser!.refreshInBackgroundWithBlock { (object, error) -> Void in
// print("Refreshed")
currentUser!.fetchIfNeededInBackgroundWithBlock { (result, error) -> Void in
self.userSchoolTF.text = currentUser!.objectForKey("school") as? String
}
}
So I have the Data before it is sent, but it shows as nil after the segue?
I suppose you created segue in Storyboard, am I right?
Put your prepareForSegue function out of tableView func. Also prepareForSegue should Override. Try using code below
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if( segue.identifier == "editParticipant" ){
if let destinationVC = segue.destinationViewController as? AddViewController {
destinationVC.LabelText = valueToPass
}
}
}
Does Swift have NSString objects? Or is String the same thing?
In objective c, assigning to an object pointer is creating a reference to the previous object. When you make it weak, it doesn't add to the reference count, so if you deallocate the original pointer, you deallocate both. Strong means that it does add to the reference count, so deallocating the first will not actually deallocate the object.
If String and NSString are two different things, try making your type NSString instead, and see if it is retained.
I work in Obj-C, not Swift, and I'm not sure of the nuances between the two.

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