Before I get started, I have to say that this project marks the first in-depth use of Swift and XCode in my life. I started it about a week ago (and am honestly impressed with how far I've gotten). I do not know too much about what I'm doing but I'm willing to learn.
Now, onto my question.
I'm trying to get a text field from one view controller to change a label from another. I thought I did it right, but it kept throwing syntax errors and such at me. After fixing that, I would run the code and get a SIGABRT error. Here's my code.
Here's the label, under BasicViewController (this isn't all that's in BasicViewController, I just cut out what I thought was pertinent)
class BasicViewController: UIViewController {
#IBOutlet weak var NameField: UILabel!
var NameText = String()
override func viewDidLoad() {
super.viewDidLoad()
NameField.text = NameText
}
And here's the text field, under EditCharController. This is where the SIGABRT error happens. (also, same thing with the lack of code.)
class EditCharController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
#IBOutlet weak var NameTextField: UITextField!
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var NameTextDest : BasicViewController = segue.destinationViewController as! BasicViewController //Specifically, this is the line that it happens at.
NameTextDest.NameText = String(NameTextField.text)
}
}
Currently, XCode is telling me to change the var label to the let label, but even if I do that, it spits out this error.
Could not cast value of type 'UITabBarController'(?!?) (0x10310c8b0) to 'Project.BasicViewController' (0x1019a0060).
Last I checked, I didn't reference the UITabBarController anywhere in the code. Why am I getting this message?
Also any suggestions as to good in-depth tutorials will be very much appreciated.
Try
let index = 0 // change this to the tab index of the BasicViewController.
let NameTextDest : BasicViewController = (segue.destinationViewController as! UITabBarController).viewControllers[index] as! BasicViewController
NameTextDest.NameText = NameTextField.text!
Related
I understand it’s rather basic, but I’m only trying to get a grasp on basic functions.
I have produced some code by partially my own knowledge and partial bits from different guides.
I am not getting any errors, but the label is not displaying itself as “Text”. I believe it’s to do with the order/place my code is put.
Please help explain how I can fix this!
Please note as well:
I have just a single label called myLabel (named under the document section of my the identity inspector
It is has the text “Loaded” put into it already when I put it in.
I have no other code anywhere, only the default new project code.
I renamed the ViewController to ViewManager to avoid a class error.
First image: This is the image just so you know the location and other bits. I’ll attach the code too:
Second image: What I get, with no errors:
Third image: My main storyboard file:
And now it in code:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var myLabel: UILabel!
#IBAction func labelSet() {
myLabel.text = "Text"
}
}
Make sure that the IBAction is connected to Touch Up Inside in Interface Builder.
Change the signature of the IBAction to
#IBAction func labelSet(_ sender: UIButton) {
Your function func labelSet() isn't called anywhere. Neither in the Storyboard nor elsewhere.
You can call it in viewDidLoad() like this:
override func viewDidLoad() {
super.viewDidLoad()
labelSet()
}
Alternatively call it after the label has loaded.
#IBOutlet weak var myLabel: UILabel! {
didSet {
labelSet()
}
}
maybe I am missing something really fundamental here, but after staring at the code for an hour or so, my brain is going trough cycles and I would appreciate a fresh glance at this problem.
I have the following UIView:
import UIKit
protocol DetailViewWillShowUpDelegate {
func sendDetailOpened(_ openedBool: Bool)
}
class locationXIBController: UIView {
#IBOutlet weak var loationLabel: UILabel!
#IBOutlet weak var vsedniOteviraciDobaLabel: UILabel!
#IBOutlet weak var prijmajiKartyLabel: UILabel!
#IBOutlet weak var detailViewButtonOutlet: UIButton!
#IBOutlet weak var backgroundViewButton: UIButton!
let openedBool = true
var detailViewWillShowUpDelegate: DetailViewWillShowUpDelegate?
override func awakeFromNib() {
super.awakeFromNib()
}
#IBAction func vecerkaDetailButtonPressed(_ sender: UIButton) {
detailViewWillShowUpDelegate?.sendDetailOpened(openedBool)
print("pressed")
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if let result = detailViewButtonOutlet.hitTest(convert(point, to: detailViewButtonOutlet), with: event) {
return result
}
return backgroundViewButton.hitTest(convert(point, to: backgroundViewButton), with: event)
}
}
Now the problem is, that when I call/press the vecerkaDetailButtonPressed function I get "pressed" output in the console but the protocol for some reason doesn't go trough.
The other side looks like this (stripped for simplicity):
class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
let locationXIB = locationXIBController()
let isVecerkaDetailOpened = false
override func viewDidLoad() {
locationXIB.detailViewWillShowUpDelegate = self
}
extension MapViewController: DetailViewWillShowUpDelegate {
func sendDetailOpened(_ openedBool: Bool) {
isVecerkaDetailOpened = openedBool
print("success")
}
}
I know the protocol value at the moment of execution is nil. As I said, any help is appreciated, thanks!
First, a couple of naming convention issues:
The name locationXIBController is a bad choice for a UIView object. It is a view object, not a controller object.
Second, class names in Swift should start with an upper-case letter. So LocationXIBView would be a much better name for that view class.
Next, your code
let locationXIB = locationXIBController()
...is wrong. That creates a brand-new instance of your locationXIBController class that you never install in your view hierarchy. You should make that line an IBOutlet:
#IBOutlet weak var locationXIB: locationXIBController!
And then you should control-drag from the locationXIBController in your StoryBoard onto the outlet in your view controller. That will cause Interface Builder to connect the outlet.
Now when you run your program the variable locationXIB will be connected to the locationXIBController view from your storyboard/XIB when it's loaded.
In addition to the answer of #Duncan C, you might check whether you need super.viewDidLoad() at the top of the viewDidLoad() method in the MapViewController class? Not doing that can lead to quirky things in your app.
I asked:
So does detailViewWillShowUpDelegate actually point at anything, or is it nil?
And you replied:
I just tried debugging and it is actually nil
So that's the problem... you need to set detailViewWillShowUpDelegate to point to a valid delegate object. This is often done in the .xib file or storyboard, and sometimes people forget to make that connection, so check there if it makes sense. Else you'll just need to get a reference to the delegate at some point before the code in question can run and set it up.
Answer to the credit of #Paulw11
I finally managed to get it working by communicating like so:
step 1) 1:1 communication via protocol between MKAnnotation and MKAnnotationView
step 2) 1:1 communication via protocol between MKAnnotationView and MapViewController passing the same data
Finally works like a charm, thanks!
I get a problem in using container view and segmented control to achieve switch views.I have put two container views in one view controller, and each of container view embed a new view(three view controller in the same UIViewController).
Here is my code
import UIKit
import Charts
class ReportViewController: UIViewController {
#IBOutlet weak var containerTwoWeeks: UIView!
#IBOutlet weak var containerToday: UIView!
#IBOutlet weak var segUi: UISegmentedControl!
#IBOutlet weak var resultLabel: UILabel!
#IBOutlet weak var paymentPie: PieChartView!
#IBOutlet weak var incomePie: PieChartView!
override func viewDidLoad() {
super.viewDidLoad()
// pieChartUpdate()
// selectResultData()
}
#IBAction func segChange(_ sender: UISegmentedControl) {
switch segUi.selectedSegmentIndex {
case 0:
self.containerTwoWeeks.isHidden = false
self.containerToday.isHidden = true
break
case 1:
self.containerTwoWeeks.isHidden = true
self.containerToday.isHidden = false
break
default:
break
}
}
func selectResultData() {
resultLabel.attributedText = reportService.selectResultData()
}
func pieChartUpdate () {
(too much code here, ignore it)
}
}
Everything works well until I called the method pieChartUpdate() or selectResultData() in vieDidLoad(),the error message as below
"Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"
I can switch the views without calling the pieChartUpdate() or selectResultData() method, so I really want to know the reason and solution.Hope someone could figure out this problem,thanks.
You got very common mistake and error. But don't worry.
Check your full error message. There must be a clue what variable you are trying to access and getting nil (it might be resultLabel).
Then make sure the connection between storyboard and view controller for this variable is correct. You can try to remove and create it again if you don't get what is wrong.
If you need more help, please show us full error message.
I am completely new to coding.
I started using this app called MIMO and learned a few bits and pieces. In one chapter they let us code a simple "dice app" where by pressing a button a number from 1 - 6 appears. Now I wanted to rewrite that so that at the button press the app displays a quote from a predetermined array.
I am completely stuck, however.
Here's what I got:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var quotesLabel: UILabel!
let quotes = ["Quote1!", "Quote2!"]
let randomIndex = Int(arc4random_uniform(UInt32(quotes.count)))
let randomQuote = quotes[randomIndex]
print(array[randomIndex])
override func viewDidLoad() {
super.viewDidLoad()
}
}
Basically any arbitrary code must be run in a method, in this case in an IBAction which is triggered when the button is pressed. The method viewDidLoad is not needed.
Change the code to
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var quotesLabel: UILabel!
let quotes = ["Quote1!", "Quote2!", "Quote3!", "Quote4!"]
#IBAction func showRandomQuote(_ sender : UIButton) {
let randomIndex = Int(arc4random_uniform(UInt32(quotes.count)))
let randomQuote = quotes[randomIndex]
quotesLabel.text = randomQuote
}
}
In Interface Builder drag a button into the canvas of the view controller
Connect (⌃-drag) the button to the IBAction and the label to the IBOutlet
Run the app and press the button
[Problem soluted!Just want to know why there is such a difference in ios8 and ios9] I was making a register view controller these days and face with some problem about weak reference.
and below is some part of the code(swift)
problem come when I use an iphone6 ios8.1
it crashed. And then I noticed that the weak reference is not proper here. But the code runs well in my ios9 iphone6s. I ran this code on an iphone6 ios8 simulator, app crashed. So I think there is some thing different in processing weak reference in ios8 and ios9, But who can explain why..?
class VC: UIViewController {
weak var verifyTextField: UITextField?
override func viewdidload() {
//....
verifyTextField = newTextField();
view.addSubview(verifyTextField!);
}
func newTextField() -> UITextField {
let ntf = UITextField();
//do some settings to ntf;
return ntf;
}
}
You set your new UITextField instance to the weak var verifyTextField but before you add it as a subview (which increments the retain count) it is deallocated (the count is 0 since the var is weak) so verifyTextField! crashes, the crash you're getting is most likely the famous
Unexpectedly found nil while unwrapping an Optional
It's easy to fix it
Don't use a weak var
Don't force unwrap (use if let instead)
The code should be as follows:
class VC: UIViewController {
var verifyTextField: UITextField? //should not be weak
override func viewdidload() {
//....
verifyTextField = newTextField()
if let verifyTextField = verifyTextField {
view.addSubview(verifyTextField!)
}
}
func newTextField() -> UITextField {
let ntf = UITextField()
//do some settings to ntf
return ntf
}
}
Looks like your object is deallocated instantly after initialization because you don't store any strong reference for it.
Try this code:
override func viewdidload() {
//....
let verifyTextField = newTextField();
view.addSubview(verifyTextField);
self.verifyTextField = verifyTextField;
}
Also no need to use weak reference here, because verifyTextField doesn't have reference to your VC, so you won't get a retain cycle.