Updating a single cell in swift UICollectionview
The cellForItemAt
method is what updates your cells. The proper way to get a cell to update is to update the model, then reload the collection view, which will call cellForItemAt
and redraw your cell based on the model.
In your case it looks like your model is self.lettersArray0
so make sure it has been updated before you call reload.
You can reload your cells using any of the following methods:
collectionView?.reloadData()
collectionView?.reloadItems(at: )
collectionView?.reloadSections(sections:)
UICollectionView update a single cell
- (void)reloadItemsAtIndexPaths:(NSArray *)indexPaths
Here it is a method to reload the specific indexPaths
in your collectionView
How to reload only one cell in a collectionView?
The problem with the lag in the collectionView can be the way tha you use NSData, consider use Alamofire Image, like this
if imageUrl.count > 0 {
let eachImage = imageUrl[indexPath.row]
Alamofire.request(eachImage).responseImage(completionHandler: {(response) in
print("answer\(response)")
if let image = response.result.value{
DispatchQueue.main.async {
cell.ImageView.image = image
}
}
})
}
iOS: reload single cell of UICollectionView
It depends on your implementation and how you have grouped your cells into sections but let's assume you have one section and each element in your array corresponds to a row in your table.
If you wanted to reload a cell corresponding to an array element at index x
all you need to do is write
[_collectionView performBatchUpdates:^{
[_collectionView reloadItemsAtIndexPaths:@[[NSIndexPath x inSection:0]]];
} completion:^(BOOL finished) {}];
Conversely, if you have the cell but want to find its index path you can always call [collectionView indexPathForCell:myCell]
How to update UICollectionView with another array when click on cell?
I have an example for you. Hope it will help you
var arr : [String] = []
var collectionView:UICollectionView!
override func viewDidLoad()
{
super.viewDidLoad()
arr = ["ONE","TWO","THREE"]
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
if indexPath.row == 1
{
arr = ["ABC", "EFG", "HIJ"]
collectionView.reloadData()
}
else if indexPath.row == 2
{
arr = ["1", "2", "3"]
collectionView.reloadData()
}
}
Xcode reload just one cell in UiCollectionView
Use the method called reloadItemsAtIndexPaths:
[self.collectionView reloadItemsAtIndexPaths:@[indexPathOfYourCell]];
UICollectionView - How to update all cells with change from one cell
Clear new cells:
Since I am not understanding your question to a 100%, I assume that your problem is that new cells get the value of cell_1, which is not something you want.
If that is the case, then there is a function called prepareForReuse
in UICollectionViewCell
.
In your subclass of the UICollectionViewCell
, implement the following:
override func prepareForReuse() {
super.prepareForReuse()
textfield.text = ""
}
That should do the trick, given that your textfield
is called textfield
.
Performs any clean up necessary to prepare the view for use again.
https://developer.apple.com/reference/uikit/uicollectionreusableview/1620141-prepareforreuse
Update all cells:
If your question is how to update other cells to get the same content as cell_1, then this means that the Collection View subclass needs to know about an update in cell_1 and then transform that update to the other cells.
One way of doing that is having your textfield
s delegate set in the Collection View. When the value is changed (textField(_:shouldChangeCharactersIn:replacementString:)
), get all the visible cells and update those textfields
accordingly. Maybe also save either a reference to the textfield
in cell_1, or a string variable in your Collection View stating the latest entered value so you can update cells as they get rendered.
You don't want to use reloadData()
though, since that will remove the focus from the textField
, since the textField
is reloaded.
Solution:
class ViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
fileprivate var customString: String?
}
extension ViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCell
cell.textField.delegate = self
cell.textField.text = customString
return cell
}
}
extension ViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
customString = string
for cell in collectionView.visibleCells {
if let cell = cell as? CustomCell,
let text = textField.text,
cell.textField != textField {
cell.textField.text = text+string
}
}
return true
}
}
The only con in the code above is that it loops through cells that currently are visible. Usually I'd recommend to stay out of looping unless absolutely necessary, but the alternative to the solution above would be to post a notification and having the cells listen to that notification and update its content accordingly. Doing that would not only be overkill, but also something notifications aren't really meant for. Third option would be to hold a weak reference in an array to every textfield, which might not be optimal as well since it creates unnecessary overhead. After all visibleCells
already is an array of the cells currently visible which each hold a reference to an UITextField
.
Can UICollectionViewUpdateItem be used to update a single label?
If you know the index path of the cell you want to update, you can get the cell using cellForItem(at: IndexPath)
. From there you can edit your cell's label.
However, I suggest you don't change your underlying data so that it's in a state that is unsuitable for presentation in the UI. The collection view can decide to create cells at times that are unpredictable to you.
UICollectionViewUpdateItem
is used to indicate e.g. from where a cell moved, and where it moved to, or that a cell at a certain position was deleted, updated, etc. The docs state:
You do not create instances of this class directly.
So it means you should only create it indirectly, for example through reloadItems(at: [IndexPath])
. It will reload your entire cell and should not be used to update a single detail of it.
Related Topics
After Upgrading to Xcode 11.2 from Xcode 11.1, App Crashes Due to _Uitextlayoutview
Xcode Suddenly Stopped Running Project on Hardware: "Could Not Launch Xxx.App: .. No Such File.."
How to Bring Application to Foreground in iOS
Decode Base-64 Encoded Png in an Nsstring
iOS Scrollview Needs Constraint for Y Position or Height
Xcode6: Run Two Instances of the Simulator
Using Core Data, Icloud and Cloudkit for Syncing and Backup and How It Works Together
Redirect Nslog to File in Swift Not Working
Unexpected Behavior When Casting an Nsnumber to Float
Sort Array of Dictionaries by Key Value
Email Validation on Textfield in iOS
Didreceiveremotenotification: Fetchcompletionhandler: Open from Icon VS Push Notification
iOS 7 Parallax Effect in My View Controller
Implementing Fast and Efficient Core Data Import on iOS 5
Nstimer Not Fired When Uiscrollview Event Occurs