Tumgik
#sort collectionview
Text
Sorting CollectionView using Orderby in C#
Sorting CollectionView using Orderby in C#
We already learned Filtering, lambad experssion on collection view, and the last one you may want to know how to get a sorted list from a collection view.
AsEnumerable () function makes it easier to sort collection view. In our example we had a StockView class which hold information for Stock of an inventory.
StockView
class StockView{ public string Batch{ get; set; } public int Qty{…
View On WordPress
0 notes
arthurknopper · 5 years
Text
Delete Items from Collection View Controller iOS Tutorial
Items inside a Collection View can be manipulated by modifying the connected model data. In this tutorial items will be removed from the Collection View Controller. This tutorial is made with Xcode 10 and built for iOS 12.
Project Setup
Open Xcode and create a new Single View App.
For product name, use IOSDeleteItemsCollectionViewTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.
Storyboard Setup
Go to the storyboard. Remove the View Controller from the Storyboard and drag a Collection ViewController to the Scene. Select the View Controller and go to the Editor Menu. Select Embed In -> Navigation Controller.
Select the Navigation Controller and go to The Attribute inspector. In the View Controller section check the "Is Initial View Controller" checkbox.
Select the Collection View Cell and go to the Attribute inspector. In the View section change the Background color to Light Gray Color.
Select The Collection View and go the Size inspector. In the Collection View section change the Cell Size to a width and height of 100 points.
Drag a Label from the Object Library and place it on the Center of the Collection View Cell.
Drag another Label to the right-bottom of the cell. This label will be needed for the state of the selection during edit mode, when selected a checkmark will be displayed. Select the label and go to the Attribute inspector. In the Label section delete the label text so the label will contain an empty string.
Select the Collection View Cell and go to the Atrribute inspector. In the Collection Reusable View section set the Identifier to "Cell".
Next, drag a Bar Button Item to the right side of the Navigation Bar. Select the Bar Button Item and go to the Attributes inspector. In the Bar Button Item section change the System Item to Trash. Also in the Bar Item section deselect the Enabled checkbox. The trash button will only be displayed when an item is selected in edit mode.
The storyboard will look like this.
Since the View Controller is removed from the Storyboard the ViewController.swift file can also be deleted from the project. Add a new file to the project, select iOS -> Source -> Cocoa Touch Class. Name it CollectionViewController and make it a subclass of UICollectionViewController.
The CollectionViewController class needs to be linked to The Collection View Controller object in the Storyboard. Select it and go the Identity Inspector. In the Custom Class section change the class to CollectionViewController
Custom Collection View Cell
Select File -> New File -> iOS -> Source -> Cocoa Touch Class. Name the class CollectionViewCell and make it a subclass of UICollectionViewCell.
Go back to Main.storyboard and select the Collection View Cell. Go to the Identity inspector and in the Custom Class section change the class to CollectionViewCell.
Outlet an Action Connections
Select the Assistant Editor and make sure the CollectionViewCell.swift file is visible. Ctrl and drag from the Title Label to the CollectionViewCell class  and create the following Outlet.
Ctrl and drag from the Checkmark Label to the CollectionViewCell class  and create the following Outlet.
Make sure the CollectionViewController.swift file is visible. Ctrl and drag from the trash bar button item to the CollectionViewController class  and create the following Outlet.
Ctrl and drag from the trash bar button item to the CollectionViewController class  and create the following Action.
Code Implementation 
Go to CollectionViewController.swift file and enter the following line.
var modelData = ["One","Two","Three","Four","Five"]
Since the Reuse Identifier is defined in the Storyboard, the following line can be removed in the CollectionViewController class
// Register cell classes self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
With the creation of the CollectionViewController class, most delegate methods are already implemented. Some methods must be tweaked a little. Change the following methods.
override func numberOfSections(in collectionView: UICollectionView) -> Int { // 1 return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // 2 return modelData.count } override func collectionView(_ collectionView: UICollectionView, cell override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // 3 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CollectionViewCell cell.titleLabel.text = modelData[indexPath.row] return cell }
By default the CollectionView only has 1 section.
The number of cells is equal to the number of items in the modelData array.
The text of the label is set to the current index of the modelData array.
Change the viewDidLoad method to
override func viewDidLoad() { super.viewDidLoad() navigationItem.leftBarButtonItem = editButtonItem }
The Edit Bar Button Item is added to the Navigation Bar. This can be used to toggle to Edit mode. Build and Run the project.
Implement Editing Mode
Go to the CollectionViewCell.swift file and add two methods.
// 1 var isInEditingMode: Bool = false { didSet { checkmarkLabel.isHidden = !isInEditingMode } } // 2 override var isSelected: Bool { didSet { if isInEditingMode { checkmarkLabel.text = isSelected ? "✓" : "" } } }
A Property Observer is created which will toggle the visibility of the checkmark label according if the coillection view controller is in editing mode or not.
Another property observer is created which will display/remove the checkmark when the cell is selected or not.
Next, go to the CollectionViewController.swift file and add the setEditing(_:animated) method
override func setEditing(_ editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) collectionView.allowsMultipleSelection = editing let indexPaths = collectionView.indexPathsForVisibleItems for indexPath in indexPaths { let cell = collectionView.cellForItem(at: indexPath) as! CollectionViewCell cell.isInEditingMode = editing } }
This method will check if a cell is in editing mode. Next add the following two methods.
// 1 override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if !isEditing { deleteButton.isEnabled = false } else { deleteButton.isEnabled = true } } // 2 override func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { if let selectedItems = collectionView.indexPathsForSelectedItems, selectedItems.count == 0 { deleteButton.isEnabled = false } }
If a cell is selected the trash icon is displayed, otherwise it remains hidden
if an cell is deselected and there are no other cells selected the trash icon is hidden.
Add the following line before the return cell line in the collectionView(_:didSelectItemAt) method
cell.isInEditingMode = isEditing
Again, this will check if a cell is in editing mode. Everything is now in place for the edtitng fucntionality. Now the actual deletion can be implemented.
Delete Items
Implement the deleteItem(_:) Action method
@IBAction func deleteItem(_ sender: Any) { if let selectedCells = collectionView.indexPathsForSelectedItems { // 1 let items = selectedCells.map { $0.item }.sorted().reversed() // 2 for item in items { modelData.remove(at: item) } // 3 collectionView.deleteItems(at: selectedCells) deleteButton.isEnabled = false } }
The selected cells will be reversed and sorted so the items with the highest index will be removed first.
the items will be removed from the modelData array
The selected cells will be deleted from the Collection View Controller and the trash icon will be disabled.
Run Project
Build and Run the project and select the Edit Button. Select a few cells and press the Trash button to remove the items.
You can download the source code of the IOSDeleteItemsCollectionViewTutorial at the ioscreator repository on Github
Related Articles
0 notes
raveenarenu-blog · 6 years
Text
An iOS developer must know
1 — Source control
Congrats you were employed! presently bring the code from the repo and get the opportunity to work. hold up what? each undertaking will require source control, regardless of whether you are the main dev. the most widely recognized ones are git and svn.
 Sync depends on a concentrated framework for form administration. it's a focal archive where working duplicates are created and a system association is required for access. its entrance approval is way based, it tracks changes by enrolling documents and the change history must be seen, completely, in the vault. working duplicates just contain the most up to date form.
 Git depends on a circulated framework for adaptation administration. you will have a neighbourhood store on which you can work, with a system association just required to synchronize. its entrance approval is for the whole catalogue, tracks changes by enrolling content and both the archive and working duplicates have the entire change history, Learn IOS training in Chennai at Greens Technologys .
Tumblr media
 2 — Architecture designs
Your fingers are jerking with energy, you made sense of source control! or on the other hand was that the espresso? doesn't make a difference! you are in the zone and it's an ideal opportunity to code! not a chance. what pause?
 Before you begin pounding your console, you need to pick a design example to set up. on the off chance that you aren't beginning the undertaking, you need to fit in with the actualized design. there is a wide cluster of examples utilized in portable application improvement, mvc, mvp, mvvm, snake, and so forth I will give you a brisk review of the most usually utilized in ios advancement:
 Mica — short for model, see, controller. the controller makes the extension between the model and the view, which are uninformed of one another. the association between the view and the controller is tight-sew, along these lines, the controller winds up taking care of pretty much everything. what does this mean? basically, in case you're fabricating a perplexing perspective, your controller (viewcontroller) will be madly enormous. there are approaches to go around this, anyway they resist the tenets of mvc. another drawback to mvc would test. on the off chance that you do tests (great on you!), you will presumably just test the model, because of it being the main layer isolate from the rest. the in addition to of utilizing the mvc design is that it's natural and most ios engineers are utilized to it.
 Mvvm — short for model, see, viewmodel. ties (essentially responsive writing computer programs) are setup between the view and the viewmodel, this permits the viewmodel to conjure changes on the model, which at that point refreshes the viewmodel, consequently refreshing the view because of the ties. the viewmodel remains unaware of the view, which encourages testing and ties decrease a ton of code.
 3 — Objective-c versus quick
 When choosing which dialect you will programme your application in, you have to realize what every dialect conveys to the table. whenever given the choice, I for one, recommend utilizing quick. why? truly objective-c has not very many favorable circumstances over quick. the vast majority of the precedents and instructional exercises are composed in target c and with each refresh to quick, changes are made to the standards, which can be debilitating. in any case, these are issues that over the long haul will blur away.
 Quick truly jumps ahead from various perspectives. it's anything but difficult to peruse, takes after characteristic english and in light of the fact that it's not based on c, it drops inheritance traditions. to the individuals who know objective-c, this implies no more semi-colons, technique calls don't require sections and no requirement for brackets to encompass restrictive articulations. it's likewise less demanding to keep up your code, quick just needs a .quick document rather than a .h and a .m record, in light of the fact that xcode and the llvm compiler can make sense of conditions and perform incremental forms naturally. by and large you should stress less over making standard code and find that you can accomplish similar outcomes with less code.
 Not persuaded? quick if more secure, quicker and deals with memory management(most of it!). know what occurs in goal c when you call a strategy with a uninitialised pointer variable? nothing. the articulation turns into a no-operation and is skipped. sounds extraordinary on the grounds that it doesn't crash the application, in any case, it prompts a progression of bugs and inconsistent conduct that will make you need to reexamine your vocation. I sh*t you not. being an expert puppy walker just turned into somewhat more engaging. quick neutralizes this with optionals. not exclusively will you have a superior thought of what can be nil and set certifications into place to counteract nil being utilized, however in the event that a nil discretionary gets utilized, quick will trigger a runtime crash, encouraging investigating. memory-wise and put essentially, bend (programmed reference including) improves quick. in target c, circular segment doesn't work for procedural c code and apis like center illustrations.
 4--To React or not to React?
 Utilitarian responsive programming (frp) is the new prevailing fashion it appears. its will likely empower simple sythesis of nonconcurrent activities and occasion/information streams.
least demanding approach to represent is with a touch of code. suppose little timmy and his sister, jenny, need to purchase another gaming console. timmy gets 5€ from his folks consistently, same goes for jenny. anyway jenny makes another 5€ by conveying daily papers on ends of the week. on the off chance that they both spare each penny, we can check each week if the support is achievable! each time one of their funds is influenced, their consolidated esteem is computed. on the off chance that it is sufficient, a message is spared in the variable isconsoleattainable. anytime we can check the message by buying in to it.
5 — Dependency administrator
Cocoapods and carthage are the most widely recognized reliance supervisors for quick and goal c cocoa ventures. they disentangle the way toward executing a library and keeping it refreshed.
Carthage is a decentralized reliance director, contrary to cocoapods. drawback to this is it turns out to be more troublesome for clients to locate the current libraries. then again, it requires less upkeep work and keeps away from any main issue of disappointment.
6 — Storing data
Let’s begin with a basic method for sparing information for your applications. nsuserdefaults, called along these lines, since it's by and large used to spare default client information, that is placed in when the application is first stacked. thus it's made to be straightforward and simple to utilize, anyway this infers a few impediments. one of it's impediments is the kind of articles it acknowledges. it acts particularly like a property list (plist), which likewise has a similar impediment. the six sort of articles they can store are the accompanying:
nsdata
nsdate
nsnumber
nsdictionary
nsstring
nsarray
To be perfect with quick, nsnumber can acknowledge the accompanying:
uint
int
skim
twofold
bool
Articles can be spared to nsuserdefaults in the accompanying way (first make a consistent that will keep the key for the protest we are sparing):
There are a few comfort strategies for perusing and writing to nsuserdefaults, that get particular questions rather than an anyobject.
Keychain is a secret phrase administration framework and can contain passwords, endorsements, private keys or private notes. the keychain has two levels of gadget encryption. the main level uses the bolt screen password as the encryption key. the second level uses a key created by and put away on the gadget.
What does this mean? it's not precisely super protected, uniquely on the off chance that you don't utilize a bolt screen password. there are likewise approaches to get to the key utilized on the second level, since it's saved money on the gadget.
Best arrangement is to utilize your own encryption. (try not to store the key on the gadget)
Coredata is a structure outlined by apple, for your application to speak with it's database in a protest arranged way. it rearranges the procedure, diminishing the code and evacuating the need to test that segment of code.
You should utilize it if your application requires tireless information, it improves the way toward holding on information a lot and means you don't need to fabricate your own particular manner of speaking with a db or testing it either.
7 — Collectionviews and tableviews
Pretty much every application has at least one gathering sees as well as table perspectives. knowing how they function, and when to utilize either, will anticipate confused changes to your application later on.
Tableviews show a rundown of things, in a solitary section, a vertical mold, and constrained to vertical looking over as it were. every thing is spoken to by a uitableviewcell, that can be totally modified. these can be arranged into areas and lines.
Collectionviews likewise show a rundown of things, be that as it may, they can have various sections and columns (lattice for instance). they can scroll on a level plane as well as vertically, and every thing is spoken to by a uicollectionviewcell. much the same as uitableviewcells, these can be redone voluntarily, and are arranged into segments and columns.
They both have comparative usefulness and utilize reusable cells to enhance ease. picking which one you require relies upon the multifaceted nature you need the rundown to have. a gathering perspective can be utilized to speak to any rundown and, as I would like to think, is dependably a decent decision. envision you need to speak to a contact list. it's straightforward, should be possible with only one segment, so you choose a uitableview. extraordinary it works! hardly any months down the line, your planner chooses that the contacts ought to be shown in framework design, rather than rundown arrange. the main way you can do this, is to change your uitableview usage to a uicollectionview execution. what i'm endeavoring to get at is, despite the fact that your rundown may be straightforward and a uitableview can do the trick, if there is a decent possibility the plan will change, it's presumably best to imlpement the rundown with a uicollectionview.
Whichever you wind up picking, it's a smart thought to make a non specific tableview/collectionview. it makes execution less demanding and enables you to reutilize a ton of code.
8 — Storyboards versus xibs versus automatic ui
Every one of these techniques can be utilized independently to make a ui, anyway nothing keeps you from joining them.
Storyboards permit a more extensive perspective of the venture, which planners love, since they can see the application stream and the majority of the screens. the drawback is that as more screens are included, the associations turn out to be all the more confounding and storyboard stack time is expanded. blend strife issues happen much more regularly, on the grounds that the entire ui has a place with one record. they are likewise much more hard to determine.
xibs give a visual perspective of screens or bits of a screen. their points of interest are simplicity of reuse, less union clashes than the storyboard approach and a simple method to perceive what's on each screen.
Programming your ui gives you a considerable measure of authority over it, less union clashes and, in the event that they do happen, are anything but difficult to fathom. drawback is the absence of visual guide and additional time it will take to program.
There are altogether different ways to deal with making your application's ui. it's very abstract, in any case, what I consider the best methodology is a mix of each of the 3. numerous storyboards (now that we can segue between storyboards!), with xibs for any visual that is anything but a principle screen and, at last, a pinch of programming for the additional control required in specific circumstances.
9 — Protocols!
Conventions exist in our day by day lives to ensure, in a given circumstance, we know how to respond. for instance, suppose you are a fire fighter and a crisis circumstance arrises. each fire fighter needs to fit in with the convention that sets the prerequisites to effectively react. the equivalent applies to a quick/objective-c convention.
A convention characterizes a draft of the strategies, properties and different necessities for given functionalities. it tends to be embraced by a class, a structure or a list, that will at that point have a real execution of those necessities.
IOS @ Greens Technologys
If you are seeking to get a good IOS training in Chennai, then Greens Technologys should be the first and the foremost option.
We are named as the best training institute in Chennai for providing the IT related trainings. Greens Technologys is already having an eminent name in Chennai forproviding the best software courses training.
We have more than 115 courses for you. We offer both online and physical training  along with the flexible timings so as to ease the things for you.
0 notes