;) hi guys!
I want delete function in MultivaluedSection,but I don't want display delete icon in section's rows, something like this:
let section2 = MultivaluedSection(multivaluedOptions: .Delete, footer: "")
for _ in 1..<4 {
section2 <<< PickerInlineRow<String> {
$0.title = "Tap to select"
$0.value = "client"
$0.options = nameList
}
}
I only want user swipe row to delete it.
I try solve it by check in Eureka source code,but can't find any method or property to do this.
FIX:
oh!I notice this code in Eureka demo->MultivaluedOnlyDeleteController->viewDidLoad:
tableView.isEditing = false
But,it seem not working at first time.user must tap edit button to reset editing status.
what's wrong with it???
To fix this issue you only have to override the viewWillAppear viewController method
override func viewWillAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableView.isEditing = false
}
Related
I'm currently working on an app that has a table-view-like collection view and some other view controllers. Basically, my question is how can I update the indexPath of each cell when one of the collection view cells is deleted.
I attached my view controller file below, but here is what's going on on the app.
When a user opens the table-view-like collection view (in EventCollectionVC), it reloads the data from a database and presents them on the collection view. I also added the code to the navigation bar button item that the user can change the collection view to the edit mode. While in the edit mode, a small ellipsis.circle (SF symbols) is displayed on the collection view cell. When a user taps the ellipsis.circle icon, it displays a new view controller (ModalVC) and lets the user select either delete or edit the cell. When the user selects delete, it shows an alert to delete the cell and delete the cell information with modal dismiss (which means the ModalVC is closed and the MyCollectionVC is displayed now).
Since I have to make the two view controllers (like getting cell information from EventCollectionVC and present in ModalVC) talk to each other, I need to use the indexPath.row to get the information of the cell. Before deleting the cells, the numbers of indexPath.row in the collection view is like
[0,1,2,3,4,5]
But, for example, after I delete the second (indexPath.row = 1) cell and when I try to delete another item, the indexPath becomes
[0,2,3,4,5]
and I can see the collection view's index is not refreshed.
So my question is how can I update/refresh the cell's indexPath.row value after I delete a cell from the collection view?
This is the code with some explanations.
import UIKit
class EvnetCollectionViewController: UIViewController {
var EventDataSource: EventDataSource! // <- this is a class for the Model, and it stores array or Events
let ListView = ListView() // view file
var collectionViewDataSource: UICollectionViewDiffableDataSource<Section, Event>?
var targetEventIndex = Int() // variable to store the index of the event when event cell is tapped
override func loadView() {
view = ListView
}
override func viewDidLoad() {
super.viewDidLoad()
configureNavItem()
setupCollectionView()
displayEvents()
}
func configureNavItem() {
navigationItem.rightBarButtonItem = editButtonItem
}
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
if (editing){
ListView.collectionView.isEditing = true
} else {
ListView.collectionView.isEditing = false
}
}
func setupCollectionView() {
let cellRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, Event> { cell, indexPath, Event in
var content = UIListContentConfiguration.cell()
content.text = Event.title
cell.contentConfiguration = content
let moreAction = UIAction(image: UIImage(systemName: "ellipsis.circle"),
handler: { _ in
let vc = EventActionModalViewController(); // when the user select the cell in edit mode, it displays action modal VC and then come back to this VC with dismiss later
vc.modalPresentationStyle = .overCurrentContext
self.targetEventIndex = indexPath.row // I need targetEvemtIndex when user selects delete event in EventActionModalVC, so just sotre value in here
})
let moreActionButton = UIButton(primaryAction: moreAction)
let moreActionAccessory = UICellAccessory.CustomViewConfiguration(
customView: moreActionButton,
placement: .trailing(displayed: .whenEditing, at: { _ in return 0 })
)
cell.accessories = [
.disclosureIndicator(displayed: .whenNotEditing),
.customView(configuration: moreActionAccessory)
]
}
collectionViewDataSource = UICollectionViewDiffableDataSource<Section, Event>(collectionView: ListView.collectionView) {
collectionView, indexPath, Event in
collectionView.dequeueConfiguredReusableCell(using: cellRegistration, for: indexPath, item: Event)
}
}
func displayEvents() {
EventDataSource = EventDataSource()
EventDataSource.loadData() // get Events in db and sore in an array Events
populate(with: EventDataSource.Events)
}
func populate(with Events: [Event]) {
var snapshot = NSDiffableDataSourceSnapshot<Section, Event>()
snapshot.appendSections([.List])
snapshot.appendItems(Events)
collectionViewDataSource?.apply(snapshot)
}
func showDeleteAlert() {
let deleteAction = UIAlertAction(title: "Delete", style: .destructive) { _ in
self.EventDataSource.delete(at: targetEventIndex)
self.refreshList()
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
self.showAlert(title: "Delete", message: nil, actions: [deleteAction, cancelAction], style: .actionSheet, completion: nil)
}
func refreshList() {
EventDataSource.loadData()
setupCollectionView() // since I write this code, it updates all of the indexPath in the collection view, but after deleting one item, the whole collection view is deleted and new collection view is reappeared.
populate(with: EventDataSource.Events)
}
}
I kinda know why this is happening. I only configure cell (in let cellRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, Event>...) once, so it won't update the cell information as well as its index path until I configure it again. But if I call setupCollectionView every after deleting one item, the whole collection view disappears and shows up again. Is it possible to reload the collection view list and updates its information without reloading the entire collection view?
Without writing setupCollectionView() in refreshList, the cell's indexPath is not refreshed and I get an error after I delete one cell and try to delete another one. So, I was wondering if there is a way to avoid recreating the whole collection view but update cells' indexPath when the user delete one of the cell in collection view.
I fixed the code in the refresh list function.
func refreshList() {
self.EventDataSource.loadData()
self.populate(with: self.EventDataSource.Events)
ListView.collectionView.reloadData()
}
I just needed to call reloadData after I populate all the data...
So in the screen recording, I want to create a search controller/search-bar like instacart has. I created a collection-view that has a search-bar in the navigation bar (via search controller). I want to show suggested searches (like instacarts' "Popular searches") when the search-bar is selected (instead of dimming the background and showing the collection-view - like its default function). And then once the user begins typing I want to have a table view that gets filtered and the filtered data gets presented (replacing the suggested searches) - like shown in the pictures. Ultimately I'm having trouble presenting suggested searches once the search-bar is clicked and presenting a filtered table once user begins typing in the search bar. Basically I would like to be able to do what instacart accomplished here. Any help would be greatly appreciated. Thanks!
Reference pictures
when you click the search bar from main category just navigate to the search suggestions.
In my case I used custom searchbar from UITextField.
I created 2 viewControllers 1 is for suggested results and other one is for showing search results.
in the searchsuggestionsVC viewDidload i am checking the character count and calling and loading suggested products in a table view as below
self.searchTF.addTarget(self, action: #selector(searchRecords(_ :)), for: .editingChanged)
create the searchRecords selecter as below
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if self.searchTF.text != "" {
//any task to perform
//if you want to dismiss your keyboard
print("Pro search keyboard button tapped")
self.proSearchQuery = self.searchTF.text ?? ""
UserDefaults.standard.set(self.proSearchQuery, forKey: "kProSearchQuery")
print("PRO SEARCH QUERY : \(self.proSearchQuery ?? "")")
self.navigatTo(identifier: "SearchResultsVC", animated: false)
}
else{
self.showCustomToast(message: "Please type something to search")
}
return true
}
And Used following delegates to navigate to the search results by tapping search button in the keyboard.
override func viewDidAppear(_ animated: Bool) {
self.searchTF.becomeFirstResponder()
}
func textFieldShouldClear(_ textField: UITextField) -> Bool {
print("text cleared")
return true
}
// search button execution
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if self.searchTF.text != "" {
//any task to perform
//if you want to dismiss your keyboard
print("Pro search keyboard button tapped")
self.proSearchQuery = self.searchTF.text ?? ""
UserDefaults.standard.set(self.proSearchQuery, forKey: "kProSearchQuery")
print("PRO SEARCH QUERY : \(self.proSearchQuery ?? "")")
self.navigatTo(identifier: "SearchResultsVC", animated: false)
}
else{
self.view.makeToast("Please type something to search")
}
return true
}
May be above code is not as per your requirements but hope you will get some Ideas on it. let me know in comments if anything not clear or add up.
I am developing an iOS app which has different forms which is populated into a UITableview based on users selection. Each form has different fields like Textfield, DatePicker, PickerView. So I used a single TableViewCell (nib) to hold all these and show or hide the items based on question.
There is save function defined which will save values when user enters to an array.
My issue is, at times my tableview scrolls as if the index goes out of control. like when I select any textfield, Tableview scrolls to top. I have removed all keyboard observer methods and checked, still it is happening.
Below is my save function code:
func saveFormValue(mystr: String) {
//selectedIndex is a global variable (NSIndexPath)
let dict = sections[selectedIndex!.section].questions![selectedIndex!.row]
dict.answer = mystr
sections[selectedIndex!.section].questions![selectedIndex!.row] = dict
let answer = updated_answer.init(ID: ID, form_id: selected_form_id, form_name: formName, section_id: dict.section_id ?? "",question_id: dict.question_id ?? "", question_name: dict.question_name!,question_type:dict.question_type!)
updatedArray.append(answer)
self.tableView.reloadData()
}
This is the code in textfieldDidBeginEditing function (how selectedIndexPath is initialized):
guard let index = tableView.indexPath(for: cell) else {
return
}
selectedIndex = index as NSIndexPath
I have added delegate for cell, and one thing I noticed is, this issue is happening whenever I press pickerview or datepicker once. I couldn't see this issue If I only touch textField cells only.
Please let me know for any further details.
Try this code hope this helps to you.
if let thisIndexPath = tableView.indexPath(for: cell) {
tableView.scrollToRow(at: thisIndexPath, at: .top, animated: false)
}
On textfield delegate method textFieldDidBeginEditing use the following code:
func textFieldDidBeginEditing(_ textField: UITextField) {
let indexParh = NSIndexPath(row: textField.tag, section: 0)
self.constTBL_Bottom.constant = 260
self.tblViewObj.scrollToRow(at: indexParh as IndexPath, at: .middle, animated: false)
}
Also you need to manage the table bottom constant. When you resigning your keyboard set table view constant to 0
Hope this will work :)
I want to know how to do two things:
Remove the UIMenuController entirely. I want the text in WKWebView to be selected, but the UIMenuController is causing issues when the long press is released.
Add a new items to the list of menu items, and remove others.
Right now I can add an item to the end of the list, but nothing else, using the following code.
func enableCustomMenu() {
let lookup = UIMenuItem(title: "Add comment", action: "addComment")
UIMenuController.sharedMenuController().menuItems = [lookup]
}
func disableCustomMenu() {
UIMenuController.sharedMenuController().menuItems = nil
}
func addComment() {
//let text = self.webView.("window.getSelection().toString();")
print("Add Comment")
}
I've spent hours trying to figure out how to create/then get a custom inputView to work.
I have a grid of TextInputs (think scrabble board) that when pressed should load a custom inputView to insert text.
I've created a .xib file containing the UI elements for the custom inputView. I was able to create a CustomInputViewController and have the inputView appear but never able to get the actual TextInput to update it's value/text.
Apple documentation has seemed light on how to get this to work and the many tutorials I've have seen have been using Obj-C (which I have been unable to convert over due to small things that seem unable to now be done in swift).
What is the overarching architecture and necessary pieces of code that should be implemented to create a customInputView for multiple textInputs (delegate chain, controller, .xibs, views etc)?
Set up a nib file with the appropriate inputView layout and items. In my case I set each button to an action on File Owner of inputViewButtonPressed.
Set up a storyboard (or nib if you prefer) for a view controller.
Then using the following code, you should get what you're looking for:
class ViewController: UIViewController, UITextFieldDelegate {
var myInputView : UIView!
var activeTextField : UITextField?
override func viewDidLoad() {
super.viewDidLoad()
// load input view from nib
if let objects = NSBundle.mainBundle().loadNibNamed("InputView", owner: self, options: nil) {
myInputView = objects[0] as UIView
}
// Set up all the text fields with us as the delegate and
// using our input view
for view in self.view.subviews {
if let textField = view as? UITextField {
textField.inputView = myInputView
textField.delegate = self
}
}
}
func textFieldDidBeginEditing(textField: UITextField) {
activeTextField = textField
}
func textFieldDidEndEditing(textField: UITextField) {
activeTextField = nil
}
#IBAction func inputViewButtonPressed(button:UIButton) {
// Update the text field with the text from the button pressed
activeTextField?.text = button.titleLabel?.text
// Close the text field
activeTextField?.resignFirstResponder()
}
}
Alternatively, if you're wanting to be more keyboard-like, you can use this function as your action (it uses the new let syntax from Swift 1.2), break it up if you need 1.1 compatibility:
#IBAction func insertButtonText(button:UIButton) {
if let textField = activeTextField, title = button.titleLabel?.text, range = textField.selectedTextRange {
// Update the text field with the text from the button pressed
textField.replaceRange(range, withText: title)
}
}
This uses the UITextInput protocol to update the text field as appropriate. Handling delete is a little more complicated, but still not too bad:
#IBAction func deleteText(button:UIButton) {
if let textField = activeTextField, range = textField.selectedTextRange {
if range.empty {
// If the selection is empty, delete the character behind the cursor
let start = textField.positionFromPosition(range.start, inDirection: .Left, offset: 1)
let deleteRange = textField.textRangeFromPosition(start, toPosition: range.end)
textField.replaceRange(deleteRange, withText: "")
}
else {
// If the selection isn't empty, delete the chars in the selection
textField.replaceRange(range, withText: "")
}
}
}
You shouldn't go through all that hassle. There's a new class in iOS 8 called: UIAlertController where you can add TextFields for the user to input data. You can style it as an Alert or an ActionSheet.
Example:
let alertAnswer = UIAlertController(title: "Input your scrabble Answer", message: nil, preferredStyle: .Alert) // or .ActionSheet
Now that you have the controller, add fields to it:
alertAnswer.addTextFieldWithConfigurationHandler { (get) -> Void in
getAnswer.placeholder = "Answer"
getAnswer.keyboardType = .Default
getAnswer.clearsOnBeginEditing = true
getAnswer.borderStyle = .RoundedRect
} // add as many fields as you want with custom tweaks
Add action buttons:
let submitAnswer = UIAlertAction(title: "Submit", style: .Default, handler: nil)
let cancel = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
alertAnswer.addAction(submitAnswer)
alertAnswer.addAction(cancel)
Present the controller whenever you want with:
self.presentViewController(alertAnswer, animated: true, completion: nil)
As you see, you have various handlers to pass custom code at any step.
As example, this is how it would look: