swift for loop working in Playground but not in the real code - for-loop

I have started using Swift: Version 6.0 (6A313)
As a newbie with Swift, I try both Playground and real code. It baffles me that this simple code works in a Playground but not when I put it into the class I want it in:
class CollectionViewCell: UICollectionViewCell {
for i in 1...3 {
println(i)
}
#IBOutlet weak var imageView: UIImageView!
}
Error message: "Expected declaration".
I appreciate any help.

Your code needs to be inside a function, for example:
class CollectionViewCell: UICollectionViewCell {
#IBOutlet weak var imageView: UIImageView!
func doSomething() {
for i in 1...3 {
println(i)
}
}
}
Otherwise there's no way to call this code, and no indication of when / how you expect it to run.

Related

Failed to set (titleText) user defined inspected property

I have a UIViewController, "MainViewController"-
class MainViewController: UIViewController {
#IBOutlet weak var segmentControl: UISegmentedControl!
#IBOutlet weak var userNameTextField: UITextField!
#IBOutlet weak var passwordTextField: UITextField!
#IBOutlet weak var controlButton: RoundedCornerButton!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func switchBetweenSignInAndRegisterOption(_ sender: UISegmentedControl) {
if sender.selectedSegmentIndex == 0{
self.controlButton.text = "Sign In"
}
else{
self.controlButton.text = "Register"
}
}
}
The action method- switchBetweenSignInAndRegisterOption(_:) attached to the segmentControl object and when its selectedSegmentIndex changes, the text property of my RoundedCornerButton is updated. The following is the code for RoundedCornerButton-
class RoundedCornerButton: UIButton {
var text: String = "Sign In"{
didSet{
setNeedsLayout()
}
}
override func layoutSubviews() {
super.layoutSubviews()
self.layer.borderWidth = 2.0
self.layer.cornerRadius = (self.bounds.size.width * 0.025)
self.layer.borderColor = UIColor.green.cgColor
self.setTitle(text, for: .normal)
self.titleLabel?.minimumScaleFactor = 0.50
}
}
It works in terms of functionality but it shows the following error in the console. I don't understand what might have gone wrong.
[ProjectName][12943:1296641] Failed to set (titleText) user defined inspected property on ([ProjectName].RoundedCornerButton):
[<[ProjectName].RoundedCornerButton 0x7f8a13d0bd90> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key titleText.
Any help would be greatly appreciated.
I found the issue though I have no idea, how it stayed in my storyboard because I removed the #IBInspectable from my CustomButton's code.
When I searched and couldn't find the titleText anywhere in my code and even in the storyboard user interface, I went to the source code of my storyboard by right clicking on it and select the source code option. To my utter surprise, there was this following code snippet-
<userDefinedRuntimeAttributes>
<userDefinedRuntimeAttribute type="string" keyPath="titleText" value="Register"/>
</userDefinedRuntimeAttributes>
Apparently even though I removed the #IBInspectable from my code, it stayed in my storyboard. I removed this part and now it works fine.

Swift 5, NSTextField, controlTextDidChange gives compiler error "Method does not override any method from its superclass"

I need to verify the characters in a NSTextField as they are being input.
I've tried every solution proposed by google and I'm now tearing my hair out because NSTextField input verification is a standard thing to do, which means that I'm failing to understand something basic.
class MyWinController: NSWindowController, NSTextFieldDelegate {
#IBOutlet var textField: NSTextField!
override func windowDidLoad() {
super.windowDidLoad()
}
#IBAction func textField(_ sender: Any) {
print("MyWinController textField")
}
override func controlTextDidChange(notification: NSNotification) {
print("APNewAPStaticWindowController controlTextDidChange")
}
}
The textField function works but when I include the controlTextDidChange function I get the compiler error: Method does not override any method from its superclass.
Help would be greatly appreciated. Thanks.

UISlider error XCode 7 Swift 2

I'm trying to build a very simple app just to see how the UISlider works. I've seen several tutorials and followed them to the letter but nothing seems to work.
I keep getting this error exactly when I try to move the Slider in the simulator, after I've successfully built
This is my whole code. It's really simple but I can't understand why the Slider won't work.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var noteBottomLabel: UILabel!
#IBOutlet weak var sliderNoteBottom: UISlider!
#IBAction func changedSliderNoteBottom(sender: AnyObject) {
var noteBottomValue = Int(sliderNoteBottom.value)
noteBottomLabel.text = "\(noteBottomValue)"
}
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.
}
Can you see any problems with this? I'm probably noobing out, but I've looked everywhere and can't find an explanation
import UIKit
import CoreFoundation
class ViewController2 : UIViewController {
override func viewDidLoad() {
super.viewDidLoad();
}
#IBOutlet weak var slider: UISlider!
#IBAction func slidervaluechanged(sender: UISlider) {
print(Int(slider.value))
}
}
I have tried your code just made the print of slider.value rather than putting it on label .
But I have used Xcode 7.3 , I don't think this should be problem with Xcode .Use the sender as UISlider when making an #IBAction that looks better . Brings up the value of 0 at bottom and 1 at top.

Swift 2.0 / iOS Unwrapping Error

I am new to Swift and am trying to make a basic application that displays a string based on entered text.
I understand that with iOS 9 and Swift 2.0, there are several new changes. I am watching a tutorial from iOS 8 and Swift 1.2 and noticed that the code I am trying to run is not compiling, stating that I need an "!" to unwrap a variable. What is the best way to learn about unwrapping and when it is necessary? A tutorial or video would be extremely helpful:
import UIKit
class ViewController: UIViewController {
#IBOutlet var resultLabel: UILabel!
#IBOutlet var age: UITextField!
#IBOutlet var convertedAge: UILabel!
#IBAction func checkAge(sender: AnyObject) {
var enteredAge = Int(age.text)
//exclamation mark "unwraps" a variable
//a way for the programmer to ensure that a value will be an int
var catYears = enteredAge! * 7
resultLabel.text = "Your cat is \(catYears)"
print(age.text)
}
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.
}
}
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html
I am suggesting apple's own source for this purpose. If you can pay for the course, also Lynda.com has a nice Swift essentials course

Detection of WebView load finish

I am creating a simple app with a WebView basing on this tutorial.
I would like to display a progress indicator while loading the page, but the methods didStartProvisionalLoadForFrame and didFinishLoadForFrame are never called. What am I doing wrong?
ViewController.swift
import Cocoa
import WebKit
class ViewController: NSViewController {
#IBOutlet weak var webView: WebView!
#IBOutlet weak var webViewProgressIndicator: NSProgressIndicator!
let messengerUrl = "https://www.messenger.com/"
override func viewDidLoad() {
super.viewDidLoad()
self.webView.mainFrame.loadRequest(NSURLRequest(URL: NSURL(string: messengerUrl)!))
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
func webView(sender: WebView!, didStartProvisionalLoadForFrame frame: WebFrame!)
{
self.webViewProgressIndicator.startAnimation(self)
}
func webView(sender: WebView!, didFinishLoadForFrame frame: WebFrame!)
{
self.webViewProgressIndicator.stopAnimation(self)
}
}
I am using Xcode 7 Beta and OS X 10.11 Beta.
Rich's answer works on Xcode 7.0.1 ElCaptain Swift2
BUT I had to connect it in the connections inspector as Swift2 did not accept
self.view.frameLoadDelegate = self
as it gave the following error
Cannot assign a value of type 'ViewController' to a value of type
'WebFrameLoadDelegate!'
So as long as you connect it up as follows, all works great.
The tutorial missed out something, Need to add:
self.webView.frameLoadDelegate = self
(can be done in connections inspector)
then call the load..
self.webView.mainFrame.loadRequest(NSURLRequest(URL: NSURL(string: messengerUrl)!))
Also add the WebFrameLoadDelegate interface to your ViewController.. (thanks tjv)
class ViewController: NSViewController, WebFrameLoadDelegate{ .....
You need to assign the delegate of your UIWebview ie: webview.delegate = self

Resources