how i can change title with RX index - swift3

I want to change title with an observable int.
in view Model
var index = Variable<Int>(0)
in view Controller
let title = ["title1","title2","title3","title4","title5"]
override func viewWillAppear(_ animated: Bool) {
self.viewModel.index.value = 0
self.viewModel.index
.asObservable()
.map( {self.periodText[$0]
})
.bind(to: self.titleLabel.rx.text)
.addDisposableTo(self.disposeBag)
}
When i do this i have an error in the blind(to) :
fatal error: unexpectedly found nil while unwrapping an Optional value
The function never pass in the .map
How i can change the title when my index change in RX Swift?

The textField on the storyBoard doesn't connect to the #IBOutlet titleLabel which
results in this error message.

My guess is your self.periodText array does not have as many elements as your index value, thus running out of bounds.
Alternatively, it could be that you're defining your diposeBag as self.disposeBag: DisposeBag!. If you've then forgotten to create an instantiation of it before viewWillAppear, it is still set to nil, in which case you'll run into this error too.
Generally, it is best to share more details on where your error occurs, so it is easier to narrow it down.

Related

SwiftUI - TextField currency input as user types

So I'm using a TextField with a formatter, the issue is unless the user hits return that value is not captured which is causing some distress for users, even though I have added a label stating they should hit return, but in fairness it doesn't seem professional. How can I combat this issue? Is there a way in which I can capture the input as the user inputs data into the textfield, as well as formatting the input simultaneously?
This is my code:
var currencyFormatter: NumberFormatter = {
let val = NumberFormatter()
val.numberStyle = .currency
val.currencyCode = "GBP"
return val
}()
TextField("0", value: $viewModel.price, formatter: currencyFormatter)
.foregroundColor(Color(SYSTEM_FONT_COLOUR))
Thank you.

What is the difference between `FileDocument` and `ReferenceFileDocument` for `DocumentGroups` in SwiftUI?

I'm trying to setup a DocumentGroup in my app, but there's no examples out there yet ReferenceFileDocument is for. I know what a FileDocument is, but how are ReferenceFileDocuments different.
In the docs all it says is:
Conformance to ReferenceFileDocument is expected to be thread-safe,
and deserialization and serialization will be done on a background
thread.
There's a hint in the name: ReferenceFileDocument is a document that's a reference type (ie, a class). FileDocument is for a struct based document.
This has an effect on how documents are saved because SwiftUI can just make a copy of the reference type and save it without worrying about you coming along and modifying it during the save, since it's a value type or tree of value types.
With ReferenceFileDocument, there also doesn't seem to be a clear way for the SwiftUI to know when to save, so it depends on you telling it. There's no direct "doc is dirty, save it now" method, so the way you inform SwiftUI that you've done something that requires saving is through the undo manager.
You also need to provide a snapshot method to return a copy of the document that's safe for it to save.
final class QuizDocument: ReferenceFileDocument, ObservableObject {
#Published var quiz: QuizTemplate
init(quiz: QuizTemplate) {
self.quiz = quiz
}
static var readableContentTypes: [UTType] { [.exampleText] }
init(configuration: ReadConfiguration) throws {
guard let data = configuration.file.regularFileContents,
let quiz = try? JSONDecoder().decode(QuizTemplate.self, from: data)
else {
throw CocoaError(.fileReadCorruptFile)
}
self.quiz = quiz
}
// Produce a snapshot suitable for saving. Copy any nested references so they don't
// change while the save is in progress.
func snapshot(contentType: UTType) throws -> QuizTemplate {
return self.quiz
}
// Save the snapshot
func fileWrapper(snapshot: QuizTemplate, configuration: WriteConfiguration) throws -> FileWrapper {
let data = try JSONEncoder().encode(quiz)
return .init(regularFileWithContents: data)
}
}
ReferenceFileDocument is a document type that will auto-save in the background. It is notified of changes via the UndoManager, so in order to use it you must also make your document undo-able.
The only mention I see of it in the docs is here.
Here is a working example.

SwiftUI ForEach does not compile with if block inside - Bug or am I doing something wrong?

I am getting an error that I don't understand. I am not sure if it is a compiler error or if I am doing something wrong?
Inside a swiftUI View I have a list showing elements from core data (Figure 1). In the example below I replaced the t.name with "yo" for some undefined reason 😅.
Anyway, the tasks is a fetch request from Core Data:
#FetchRequest(entity: Task.entity(), sortDescriptors: []) var tasks: FetchedResults<Task>
FIGURE 1: Works fine to build and run the app.
FIGURE 2: Does not work to build and run the app.
Please help me understand what I am doing wrong or is this a compiler bug? Why can't I add the if block inside the ForEach? I can provide more information if needed. Thanks!
You can use if inside ForEach, but you should remember that ForEach is not language operator foreach but a struct type with ViewBuilder in constructor with generics in declaration, so it needs to determine type, which in your case it cannot determine.
The possible solution is to tell explicitly which type you return, as below (tested with Xcode 11.2 / iOS 13.2)
ForEach(tasks, id: \.id) { name -> Text in
if (true) {
return Text("name")
}
}
You have to return nil in case of a false condition. So you need to declare parameter as Optional and return nil in case of a false condition (XCode - 11.3.1).
ForEach(tasks, id: \.id) { t -> Text? in
return condition ? Text("text") : nil
}
}
For some reason, in the ForEach.init you're using, the view building closure isn't annotated with #ViewBuilder. This means that the if/else you're using is Swift's own if statement, not the SwiftUI construct which returns a _ConditionalContent.
I don't know if it's considered a bug by Apple, but I would definitely consider it to be one.
The easiest workaround is just to wrap the if/else in a Group - the Group.init is a #ViewBuilder, so will handle the if/else correctly.
What also worked for me was using a Group inside the ForEach like this:
ForEach(self.items, id: \.self { item in
Group {
if item.id == 0 {
Text(String(item.id))
}
}
}

Swift Delegation: unexpectedly found nil while unwrapping an Optional value

Edit: Please note the question below discusses using delegation between
2 viewcontrollers that are also implemented in a UITabBarController.
I've done a fair bit of searching here and on YouTube, but haven't seen my issue replicated elsewhere. I'll keep it to the point.
I have 2 view controllers that I coded myself -not generated by XCode-; TabOneController, and TabTwoController
below are the coding for both...
import UIKit
class TabOneController: UIViewController{
private let instanceOfTabOneView = TabOneView()
var vc1Delegate: fromOneToTwo!
override func loadView() {
super.loadView()
view.addSubview(instanceOfTabOneView.buildTheVu())
view.backgroundColor = UIColor.white
runThisOnce()
}
func runThisOnce(){
vc1Delegate.passTheValue(heroNameIs: "pass this to TabTwoController")
}
}
protocol fromOneToTwo{
func passTheValue(heroNameIs: String)
}
as for tab 2...
import UIKit
class TabTwoController: UIViewController, fromOneToTwo{
private let instanceOfTabTwoView = TabTwoView()
override func loadView() {
super.loadView()
view.addSubview(instanceOfTabTwoView.buildTheVu())
assignDelegateToSelf()
}
func assignDelegateToSelf(){
let instanceTabOne = TabOneController()
instanceTabOne.vc1Delegate = self
}
func passTheValue(heroNameIs:String){
instanceOfTabTwoView.txtFld.text = heroNameIs
}
}
I'm getting the following error at runtime -the app builds successfully-...
fatal error: unexpectedly found nil while unwrapping an Optional value
on the following line...
vc1Delegate.passTheValue(heroNameIs: "pass this to TabTwoController")
When I comment out the above line, the app builds and runs successfully, but of course the app doesn't execute the delegation.
I kinda understand what the compiler is trying to tell me, that the
vc1Delegate
hasn't been instantiated -I guess-. But I searched under every rock, and can't seem to find how to get around this.
I'd appreciate any help or guidance. Sorry if my code seems immature, I'm new to Swift and programming in general. Thank you.
In a UITabBarController, the first tab is instantiating by default. The view controller initialization executes the loadView and finds a nil because the second tab did not initialize yet; this is normal behavior. My suggestion is making the delegate weak optional with the ? suffix and run the delegate code elsewhere. Also, always capitalize the first letter in class and protocol names.
weak var vc1Delegate: FromOneToTwo?
If this structure is mandatory, try with a custom notification observer instead.
First thing first, your error happens in line var vc1Delegate: fromOneToTwo! while you declared this delegate variable as not null but then calling passTheValue on it. A correct practice will be
var vc1Delegate: fromOneToTwo?
func runThisOnce(){
if let delegate = vc1Delegate {
vc1Delegate.passTheValue(heroNameIs: "pass this to TabTwoController")
}
}
Secondly, you are not using delegate correctly. In the assignDelegateToSelf() function, you are creating a new instance of TabOneController
and then assign delegate. Instead, you need to find out the existing TabOneController instance and assign delegate.
I try this and worked add delegate = self in table cellforRowAt
like this
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "ChapterPracticeTableViewCell") as! ChapterPracticeTableViewCell
cell.deligate = self
return cell
}

Handlebars block helper inside quotes

don't know if block helper is the right name but hope you get the point.
In Ember 1.8.0-beta.2 i can not do
<img src="{{url}}">
Chrome gives me:
Uncaught TypeError: Cannot read property 'parentNode' of null
Uncaught TypeError: Cannot set property 'profileNode' of undefined
And Firefox gives me:
TypeError: ref is null
var parent = ref.parentNode;
The error comes from vendor.js
hydrateMorphs: function () {
var childViews = this.childViews;
var el = this._element;
for (var i=0,l=childViews.length; i<l; i++) {
var childView = childViews[i];
var ref = el.querySelector('#morph-'+i);
var parent = ref.parentNode; // This line
childView._morph = this.dom.insertMorphBefore(parent, ref);
parent.removeChild(ref);
}
}
I know that i simply can do a handlebars helper to output the img tag with right src but i want to be able to use the {{url}} to set a divs background property aswell.
(the url property is just a simplified version. In my app i have a helper thats takes an array of images and maxWidth to to give me the best picture depending on the width. But {{url}} does not work either)
forgot that I just can use unbound:
<img src="{{unbound url}}">
You can't use that syntax in ember handlebars. The accepted one is bind-attr.
Usage examples: http://emberjs.com/guides/templates/binding-element-attributes/
More info: http://www.emberist.com/2012/04/06/bind-and-bindattr.html