Absolute Swift beginner here.
I have been trying to get a simple set of png's to animate.
Here is what I have:
Any help would be much appreciated.
Thanks
#import <UIKit/UIKit.h>
class ViewController: UIViewController {
#IBOutlet var myImageView : UIImageView
#IBOutlet var animationBtn : UIButton
var imageList = UIImage[]()
#IBAction func animationBtnClicked(sender : AnyObject) {
startAnimation()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
for i in 1...13
{
let imageName = "\(i)"
imageList += UIImage(named: imageName)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func startAnimation() -> Void
{
if !myImageView.isAnimating()
{
myImageView.animationImages = imageList
myImageView.startAnimating()
animationBtn.setTitle("Stop Animation", forState: UIControlState.Normal)
} else
{
myImageView.stopAnimating()
myImageView.image = UIImage(named:"bomb.jpg")
animationBtn.setTitle("Start Animation", forState: UIControlState.Normal)
}
}
}
Here is the adjusted code if it helps anyone.
Cheers
import UIKit
class ViewController: UIViewController {
#IBOutlet var myImageView: UIImageView!
#IBOutlet var animationBtn: UIButton!
var imageList = [UIImage]()
#IBAction func animationBtnClicked(sender: AnyObject) {
startAnimation()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
for i in 1...99
{
let imageName = "\(i)"
imageList.append(UIImage(named: imageName)!)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func startAnimation() -> Void
{
myImageView.animationImages = imageList
myImageView.startAnimating()
}
}
Those errors messages shows the exact issue.
Issue 1
For fixing has no initializers, you need implement at-least one init function in your class.
Issue 2
For fixing IBOutlet has non-optional, you need to change your IBOutlet variables to optionals.
#IBOutlet var myImageView : UIImageView!
#IBOutlet var animationBtn : UIButton!
Issue 3
For fixing that [UIImage] is not identical to UInt8. The += can't be used to append a single UIImage to [UIImage]
You need to change:
imageList += UIImage(named: imageName)
to
imageList.append(UIImage(named: imageName))
Related
I want to create a simple BMI calculator using height and weight and I am having trouble converting my UITextField strings to integers for the calculation.
Here's my working code:
import UIKit
class BMICalculator: UIViewController {
//MARK: Properties
#IBOutlet weak var weightField: UITextField!
#IBOutlet weak var heightField: UITextField!
#IBOutlet weak var solutionTextField: UILabel!
#IBAction func calcButton(_ sender: AnyObject) {
let weightInt = Int(weightField)
let heightInt = Int(heightField)
solutionTextField.text = weightInt/(heightInt*heightInt)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Anyone have any ideas? I tried searching for the solution but couldn't find anything specific to this issue.
Use this:
guard let text1 = weightField.text else {
return
}
guard let text2 = heightField.text else {
return
}
guard let weightInt = Int(text1) else {
return
}
guard let heightInt = Int(text2) else {
return
}
solutionTextField.text = weightInt /(heightInt*heightInt)
//Change your name for this outlet 'solutionTextField' to 'solutionLabel' since it is a UILabel not UITextField
The TextField only accepts a String, it wont take an Int.
Change this:
solutionTextField.text = weightInt/(heightInt*heightInt)
To this:
solutionTextField.text = String(weightInt/(heightInt*heightInt))
I don't think your code is working. To get the values out of your UITextFields and convert them to Ints, you'll need to pull them out of the '.text properties. Then, when you calculate the result, you'll need to convert it back to a string and set solutionTextField?.text equal to that result.
class BMICalculator: UIViewController {
//MARK: Properties
#IBOutlet weak var weightField: UITextField!
#IBOutlet weak var heightField: UITextField!
#IBOutlet weak var solutionTextField: UILabel!
#IBAction func calcButton(_ sender: AnyObject) {
let weightInt = Int((weightField?.text!)!)
let heightInt = Int((heightField?.text!)!)
let solution = weightInt!/(heightInt!*heightInt!)
solutionTextField?.text = "\(solution)"
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Keep in mind that this code is very dangerous because you're not safely unwrapping optionals, but that's a different thread.
Hope this helps.
I'm very new to all of this and I found some code that got me understanding some of this syntax. I'm trying to create a textfield that lets me type in a value that updates the stepper's value. The stepper currently works (updates the uitextfield) but when I change the value in the textfield it doesn't update the stepper's value, so when I click on the stepper, it reverts back to whatever value it was before I typed in a value... Can anyone tell me why the two functions STracksValueDidChange and CTrackValueDidChange have errors?
Here's my code so far:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var STracks: UITextField!
#IBOutlet weak var STracksStepper: UIStepper!
#IBOutlet weak var CTracks: UITextField!
#IBOutlet weak var CTrackStepper: UIStepper!
override func viewDidLoad() {
super.viewDidLoad()
STracksStepper.autorepeat = true
STracksStepper.maximumValue = 100.0
STracksStepper.minimumValue = 2.0
STracksStepper.stepValue = 2.0
print(STracksStepper.value)
STracks.text = "\(Int(STracksStepper.value))"
STracksStepper.addTarget(self, action: "SstepperValueDidChange:", forControlEvents: .ValueChanged)
STracks.addTarget(self, action: "STextValueDidChange:", forControlEvents: .ValueChanged)
CTrackStepper.autorepeat = true
CTrackStepper.maximumValue = 100.0
CTrackStepper.minimumValue = 2.0
CTrackStepper.stepValue = 2.0
print(CTrackStepper.value)
CTracks.text = "\(Int(CTrackStepper.value))"
CTrackStepper.addTarget(self, action: "CstepperValueDidChange:", forControlEvents: .ValueChanged)
CTracks.addTarget(self, action: "CTextValueDidChange:", forControlEvents: .ValueChanged)
}
//Steppers will update UITextFields
func SstepperValueDidChange(stepper: UIStepper) {
let stepperMapping: [UIStepper: UITextField] = [STracksStepper: STracks]
stepperMapping[stepper]!.text = "\(Int(stepper.value))"
}
func STracksValueDidChange(SText: UITextField) {
let STextMapping: [UITextField: UIStepper] = [STracks: STracksStepper]
STextMapping[SText]!.value = "(SText.text)"
}
func CstepperValueDidChange(stepper: UIStepper) {
let stepperMapping: [UIStepper: UITextField] = [CTrackStepper: CTracks]
stepperMapping[stepper]!.text = "\(Int(stepper.value))"
}
func CTrackValueDidChange(CText: UITextField) {
let CTextMapping: [UITextField: UIStepper] = [CTracks: CTrackStepper]
CTextMapping[CText]!.value = "(CText.text)"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Try something like this.
CTrackStepper.value = Double(Textfield.text)
I am not so sure what the mapping is in your code.
But i don't think you need it for changing the value.
Update, made a project my self:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var textfield: UITextField!
#IBOutlet weak var stepper: UIStepper!
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.
}
#IBAction func stepperValueChanged(sender: UIStepper) {
textfield.text = String(sender.value)
}
#IBAction func valueChanged(sender: UITextField) {
if Double(sender.text!) != nil {
stepper.value = Double(sender.text!)!
}
}
}
For steppervaluechanged and valuechanged just drag from uistepper and textfield and choose action and change the Anyobject to Uistepper of Uitextfield.
Good luck :)
So i am making an iOS app, that lets you to enter text into a TextBox and then there is a Button that will display the "Text" on a label, and that "Text" on the label will be Displayed in the Notification Center, on a widget, But something is going wrong Because every time i run the app it fails and throws me into the AppDelegate.Swift and highlights me this specific part: "class AppDelegate: UIResponder, UIApplicationDelegate {"
with an error that says "Thread 1: signal SIGABRT"
i Don't know what else to do ;( please help!!
This is the ViewController.Swift code:
import UIKit
class ViewController: UIViewController {
#IBOutlet var UserInput: UITextField!
#IBOutlet var TextDisplay: UILabel!
#IBAction func DisplayButton(sender: AnyObject) {
let Text:String = UserInput.text!
if let Text = Int(Text) {
print("Computer says no!")
} else {
TextDisplay.text = (Text)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let SharedDefaults = NSUserDefaults(suiteName: "group.St33v3n.TextOnWidget")
SharedDefaults?.setObject(UserInput, forKey: "StringKey")
SharedDefaults?.synchronize()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
and Here is the TodayView controller code (the one from the widget):
import UIKit
import NotificationCenter
class TodayViewController: UIViewController, NCWidgetProviding {
#IBOutlet var TextToWidget: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view from its nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)) {
let ShareDefaults = NSUserDefaults(suiteName:"group.St33v3n.TextOnWidget")
self.TextToWidget.text = ShareDefaults?.objectForKey("StringKey") as? String
completionHandler(NCUpdateResult.NewData)
}
}
In the line
SharedDefaults?.setObject(UserInput, forKey: "StringKey")
you are passing UITextField object, not the text. You should use
SharedDefaults?.setObject(UserInput.text, forKey: "StringKey")
I'm not sure if that is causing the crash, but it needs correction anyway ;)
The purpose for my app
I have two ViewControllers,FrontSideViewController and BackSideViewController, in my little project.
I am about to flipping FrontSideViewController to BackSideViewController through using CATransition while each ViewController's data can be saved.
Describe of Problem
The views transited in the unexpected way which animation is not seem like the UIAnimationTransition.FlipFromLeft(or)Right thing.
After flipping views, the previous view's data can not be saved, which means when I flipped back the old view, its tiny data (something like textField's text) is just gone.
My Code
Same Logical function to flip between the views which be used in two Classes.
FrontSideViewController.swift
class FrontSideViewController: UIViewController {
var frontSideViewController: FrontSideViewController?
var backSideViewController: BackSideViewController?
var frontSide: Bool = true
#IBOutlet weak var flip_1Button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
frontSideViewController = storyboard?.instantiateViewControllerWithIdentifier("FrontSideViewController") as? FrontSideViewController
backSideViewController = storyboard?.instantiateViewControllerWithIdentifier("BackSideViewController") as? BackSideViewController
flip_1Button.addTarget(self, action: "flipViews", forControlEvents: UIControlEvents.TouchUpInside)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func textFieldDoneEditing(sender: UITextField) {
sender.resignFirstResponder()
}
func flipViews() {
UIView.beginAnimations("ViewSwitch", context: nil)
UIView.setAnimationDuration(0.6)
UIView.setAnimationCurve(.EaseInOut)
UIView.setAnimationTransition(.FlipFromLeft, forView: view, cache: true)
backSideViewController?.view.frame = self.view.frame
frontSideViewController?.willMoveToParentViewController(nil)
frontSideViewController?.view.removeFromSuperview()
frontSideViewController?.removeFromParentViewController()
self.addChildViewController(backSideViewController!)
self.view.addSubview(backSideViewController!.view)
backSideViewController?.didMoveToParentViewController(self)
}
}
BackSideViewController.swift
class BackSideViewController: UIViewController {
var frontSideViewController: FrontSideViewController?
var backSideViewController: BackSideViewController?
#IBOutlet weak var flip_2Button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
frontSideViewController = storyboard?.instantiateViewControllerWithIdentifier("FrontSideViewController") as? FrontSideViewController
backSideViewController = storyboard?.instantiateViewControllerWithIdentifier("BackSideViewController") as? BackSideViewController
flip_2Button.addTarget(self, action: "flipViews", forControlEvents: UIControlEvents.TouchUpInside)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func flipViews() {
UIView.beginAnimations("ViewSwitch", context: nil)
UIView.setAnimationDuration(0.6)
UIView.setAnimationCurve(.EaseInOut)
UIView.setAnimationTransition(.FlipFromRight, forView: view, cache: true)
frontSideViewController?.view.frame = self.view.frame
backSideViewController?.willMoveToParentViewController(nil)
backSideViewController?.view.removeFromSuperview()
backSideViewController?.removeFromParentViewController()
self.addChildViewController(frontSideViewController!)
self.view.addSubview(frontSideViewController!.view)
frontSideViewController?.didMoveToParentViewController(self)
}
Please teach me how solve those two problems.
Thanks for your help.
Ethan Joe
I want to have a UIScrollView of UIViewControllers. I tested the ScrollView and it works fine, except when I try to add the ViewControllers. The project builds fine, but I get a "fatal error: unexpectedly found nil while unwrapping an Optional value" error that points at the ViewController, particularly the line:
self.imageView.image = UIImage(named: self.image!)
However, when I inspect the object, I can see variables image and text have values in the ViewController. I'm using Xcode 6.3 Beta and building to iOS8.1 target.
Here's the code:
import UIKit
class ViewController: UIViewController {
//#IBOutlet weak var contentScrollView: UIScrollView!
#IBOutlet var contentScrollView: UIScrollView!
//test to make sure ScrollView functions
//let colors = [UIColor.redColor(),UIColor.blueColor(), UIColor.greenColor(), UIColor.whiteColor(), UIColor.blackColor(), UIColor.yellowColor()]
var frame = CGRectMake(0, 0, 0, 0)
var dataArray = [PostItem]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var da = PostItem(text: "test 1", pic: "beans.jpg")
self.dataArray.append(da!)
da = PostItem(text: "test 2", pic: "coffee.jpg")
self.dataArray.append(da!)
da = PostItem(text: "test 3", pic: "coffeeCup.jpg")
self.dataArray.append(da!)
for index in 0..<self.dataArray.count{
self.frame.origin.y = self.contentScrollView.frame.size.height * CGFloat(index)
self.frame.size = self.contentScrollView.frame.size
self.contentScrollView.pagingEnabled = false
let tempPost = self.dataArray[index]
var vc = PostViewController()
vc.text = tempPost.postText
vc.image = tempPost.postImage
self.contentScrollView.addSubview(vc.view)
}
self.contentScrollView.contentSize = CGSizeMake(self.view.frame.size.width, CGFloat(self.dataArray.count) * self.contentScrollView.frame.height)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}}
And here is the code for the ViewController I want to add:
import UIKit
class PostViewController: UIViewController {
//let postItem
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var postToFBButton: UIButton!
#IBOutlet weak var postToTwitterButton: UIButton!
#IBOutlet weak var postText: UILabel!
var image:String?
var text:String?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.imageView.image = UIImage(named: self.image!)
self.postText.text = text!
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}}
The fix is to create the PostViewController through instantiateViewControllerWithIdentifier from storyboard, this way, it will have an imageView loaded from storyboard when its view is added to the scrollview.