Iterating through texts and putting them in one uitextview - ios

I get JSON response from the web and I successfully printing items out on the console using below code:
for game in listOfRecentGames {
if let statInfoForTheGame = game["stats"] as? [String : String] {
var text = statInfoForTheGame["info"]
}
}
There are multiple number of games in listOfRecentGames. I get a string value of information for each game and I would like to show every of them in one UITextView. How can I achieve this? I was thinking about putting in array and printing out in UITextView but not sure.

You actually won't need an array to do that. You already have the textView's existing text, so you just can append the new text to the existing one.
Code
let listOfRecentgames = [
["stats": ["info": "Something1"]],
["stats": ["info": "Something2"]],
["stats": ["info": "Something3"]]
]
var textViewText = yourTextView.text
for game in listOfRecentgames {
if let statInfoForTheGame = game["stats"] {
if let text = statInfoForTheGame["info"] {
textFieldText.appendContentsOf(" \(text)")
}
}
}
// Now you have the whole information from each game so just bind it to the textView
yourTextView.text = textViewText
Playground output

Related

Append Dictionary, iOS, Swift

I am trying to edit my code that I created that is posting text to firebase. I was originally only allowing 8 pictures and descriptions no more, no less. I am now refactoring so the user can pick any number up to 8. I have the checks for the photos working and it uploads the amount picked. I have put checks in place to see if there is a picture or not and if there is it will show the text box to add a description otherwise it is hidden. My problem is I have a dictionary that posts to firebase that is posting 8 descriptions so if i was to create 2 it would fill the other 6 with "" is there a way to check that if an image is nil like I do above then it adds to the dictionary to upload. My function is below..
func postToFirebase() {
let post: Dictionary<String, AnyObject> = [
"photoInfo1": photoInfo1.text as AnyObject,
"photoInfo2": photoInfo2.text as AnyObject,
"photoInfo3": photoInfo3.text as AnyObject,
"photoInfo4": photoInfo4.text as AnyObject,
"photoInfo5": photoInfo5.text as AnyObject,
"photoInfo6": photoInfo6.text as AnyObject,
"photoInfo7": photoInfo7.text as AnyObject,
"photoInfo8": photoInfo8.text as AnyObject
]
let firebasePost = DataService.ds.REF_BASE.child("posts").child("\(stringPassed)")
firebasePost.updateChildValues(post)
}
The check I'm doing before this to hide the boxes are..
if passImage2 == nil {
photo2.isHidden = true
photoInfo2.isHidden = true
}
and so on.
I was hoping I could do a check to see if the photo is not nil then if so append the "post" dictionary rather than have them all already coded in.
If you don't need your photoInfo to be continuos in numbering, you can use
let filtered = post.filter { (key, value) -> Bool in
guard let stringValue = value as? String else { return false }
return stringValue != ""
}
If you need it to be continuos you can filter an array of label texts and then with using of enumarated and reduce, you can create a new dictionary.

Save tableview textfields to an array of custom objects

I´m searching for a way to save the data a user enters in two textfields in a tableview. The user has to enter the name and the height of person in a tableview and I want to save it to a custom array.
struct PersonData {
var name: String
var height: Int
init(name: String, height: Int) {
self.name = name
self.height = height
}
}
I´ve searched and i found this Swift: retrieving text from a UITextField in a custom UITableViewCell and putting it in an array but still got two questions.
How i add item to my custom array? I try it with this:
personData[textField.tag].name = textField.text!
Isn´t a easier way to do it?
Thank you!!
If I understood your question properly then heres a possible solution.
You initialise an array of type PersonData. Then you make an object of type PersonData. Whenever you have some info, you store it in this object and append the object to the array created.
let array = [PersonData]()
let personDataObject = PersonData()
//After you store the values in the object you add the object to you array.
personDataObject.name = textField1.text
personDataObject.height = textField2.text //You need to convert this to Int. Try personDataObject.height = textField2.text as? Int or personDataObject.height = Int(textField2.text)
array.append(personDataObject)

Swift - filter Realm objects via UISearchBar in a UICollectionView

This is my Realm object, basically an image with some tag attached.
class AllTags: Object {
dynamic var singleTag = ""}
class Photo: Object {
var myTags: [String] {
get {
return _backingNewTags.map { $0.singleTag }
}
set {
_backingNewTags.removeAll()
_backingNewTags.appendContentsOf(newValue.map({ AllTags(value: [$0]) }))
}
}
let _backingNewTags = List<AllTags>()
override static func ignoredProperties() -> [String] {
return ["myTags"]
}
dynamic var imagePath = ""}
I have my collectionView, I can see all my photo and when pressing an image I can see my tags, so everything is working correctly.
I have added my UISearchBar, added the txtSearchbar.delegate = self and using let data = realm.objects(AllTags).map { $0.singleTag } I can print ALL the tags inside my database.
I just need to filter in real time while I type the CollectionView cells via the UISearchBar so it shows only the images tagged with the word I'm typing. Basic.
I've been following this tutorial to filter in the collectionView - https://github.com/codepath/ios_guides/wiki/Search-Bar-Guide#example-searching-a-collection-view - After 11 hours, I can't figure out how to make it works with Realm. With hardcoded Array like the example I can make it works.
In Realm, you can filter a Results<T> based on what you're looking for. For example:
let data = realm.objects(AllTags).filter("singleTag CONTAINS %#", searchTerm)
I'm wondering, however, why you're converting your _backingNewTags to an Array [String]? Why can't you just access the tags directly? This will be much more memory & CPU efficient, and will simplify your code...

How to get the current word being typed?

I am making a custom keyboard extension for iOS 8 and am unsuccessful at trying to reflect the current word being typed on a UILabel sitting on top of the keyboard (think autocorrect). So far the code I wrote reflects the sentence before the cursor and not as it's being written, but as the cursor is moved from one position to another. What I am trying to achieve is exactly like the first autocorrect box in the native keyboard. Would anyone mind telling me what I am doing wrong?
Code:
override func textWillChange(textInput: UITextInput) {
var tokens = (self.textDocumentProxy as! UITextDocumentProxy).documentContextBeforeInput .componentsSeparatedByString(" ") as NSArray
var lastWord = tokens.lastObject as! String
println(lastWord)
bannerView?.btn1.setTitle(lastWord, forState: .Normal)
}
I've tried setting a condition whereby if beforeCursor contained either a space/period/comma to set the button title as "" but that is not efficient in the long run as I need to obtain words in order to be able to make an autocorrect feature.
Edit:
I've figured out how to get the word before the cursor (updated the code above), but not how to update the label as each letter is being added. func textWillChange(textInput: UITextInput)isn't working out. It's not me it's her.
Thanks!
You should use the textDocumentProxy property of your UIInputViewController:
let proxy = self.textDocumentProxy as! UITextDocumentProxy
To get the word being typed, I would suggest something like this:
var lastWordTyped: String? {
if let documentContext = proxy.documentContextBeforeInput as NSString? {
let length = documentContext.length
if length > 0 && NSCharacterSet.letterCharacterSet().characterIsMember(documentContext.characterAtIndex(length - 1)) {
let components = documentContext.componentsSeparatedByCharactersInSet(NSCharacterSet.alphanumericCharacterSet().invertedSet) as! [String]
return components[components.endIndex - 1]
}
}
return nil
}

When creating a series of NSTextContainers, how do I specify container breaks based on the text content?

I'm creating a series of NSTextContainers to hold the text from an HTML resource. I am able to add the HTML to an attributed string, assign that to a NSTextStorage and NSLayoutManager, and create a series of NSTextContainers to hold all the text.
My problem is, I want to add "page breaks" within the text, i.e. stop filling this text container and start another... In the documentation, I've found something call NSControlCharacterContainerBreakAction; but I'm unclear how to implement it or if thats even the best approach.
Code snippet below is how I'm current building by text containers (in Swift).
var myLayoutManager = NSLayoutManager()
var myText:NSAttributedString = {
let path = NSBundle.mainBundle().URLForResource("localfile", withExtension: "html")
let opts = [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType]
return NSMutableAttributedString(fileURL: path, options: nil, documentAttributes: nil, error: nil)!
}()
myTextStorage = NSTextStorage(attributedString: myText)
myTextStorage.addLayoutManager(myLayoutManager)
//Create all textContainers to hold text
if myLayoutManager.textContainers.count == 0 {
var range = NSMakeRange(0, 0)
while(NSMaxRange(range) < myLayoutManager.numberOfGlyphs) {
var myTextContainer = NSTextContainer(size: CGSizeMake(450, 580))
myLayoutManager.addTextContainer(myTextContainer)
range = myLayoutManager.glyphRangeForTextContainer(myTextContainer)
}
}
You can just put "Page Break" ASCII control character in your string, layout manager will handle it.
let pageBreakString = String(UnicodeScalar(12))
Reference: ASCII Control Character

Resources