How to replicate the search selection on iOS's Mail app? - ios

I have a list with a .searchable search bar on top of it. It filters a struct that has text, but also a date.
I'm trying to have the user select whether he/she wants to search for all items containing the specific text, or search for all items with a data. I thought the way that iOS Mail did it when you hit he search bar on top is a good way (I'm open to other options tho...).
It looks like this:
So, when you tap the search field, the picker, or two buttons, or a tab selector shows up. I can't quite figure which is it. Regardless, I tried with a picker, but:
I don't know where to place it
I don't know how to keep it hidden until needed, and then hide it again.
this is the basic code:
let dateFormatter = DateFormatter()
struct LibItem: Codable, Hashable, Identifiable {
let id: UUID
var text: String
var date = Date()
var dateText: String {
dateFormatter.dateFormat = "EEEE, MMM d yyyy, h:mm a"
return dateFormatter.string(from: date)
}
var tags: [String] = []
}
final class DataModel: ObservableObject {
#AppStorage("myapp") public var collectables: [LibItem] = []
init() {
self.collectables = self.collectables.sorted(by: {
$0.date.compare($1.date) == .orderedDescending
})
}
func sortList() {
self.collectables = self.collectables.sorted(by: {
$0.date.compare($1.date) == .orderedDescending
})
}
}
struct ContentView: View {
#EnvironmentObject private var data: DataModel
#State var searchText: String = ""
var body: some View {
NavigationView {
List(filteredItems) { collectable in
VStack(alignment: .leading) {
Spacer() Text(collectable.dateText).font(.caption).fontWeight(.medium).foregroundColor(.secondary)
Spacer()
Text(collectable.text).font(.body).padding(.leading).padding(.bottom, 1)
Spacer()
}
}
.listStyle(.plain)
.searchable(
text: $searchText,
placement: .navigationBarDrawer(displayMode: .always),
prompt: "Search..."
)
}
}
var filteredItems: [LibItem] {
data.collectables.filter {
searchText.isEmpty ? true : $0.text.localizedCaseInsensitiveContains(searchText)
}
}
}
And I was trying to add something like, taking into account isSearching:
#Environment(\.isSearching) var isSearching
var searchBy = [0, 1] // 0 = by text, 1 = by date
#State private var selectedSearch = 0
// Yes, I'd add the correct text to it, but I wanted to have it
// working first.
Picker("Search by", selection: $selectedColor) {
ForEach(colors, id: \.self) {
Text($0)
}
}
How do I do it? How can I replicate that search UX from Mail? Or, is there any better way to let the user chose whether search text or date that appears when the user taps on the search?

isSearching works on a sub view that has a searchable modifier attached. So, something like this would work:
struct ContentView: View {
#EnvironmentObject private var data: DataModel
#State var searchText: String = ""
#State private var selectedItem = 0
var body: some View {
NavigationView {
VStack {
SearchableSubview(selectedItem: $selectedItem)
List(filteredItems) { collectable in
VStack(alignment: .leading) {
Spacer()
Text(collectable.dateText).font(.caption).fontWeight(.medium).foregroundColor(.secondary)
Spacer()
Text(collectable.text).font(.body).padding(.leading).padding(.bottom, 1)
Spacer()
}
}
.listStyle(.plain)
}.searchable(
text: $searchText,
placement: .navigationBarDrawer(displayMode: .always),
prompt: "Search..."
)
}
}
var filteredItems: [LibItem] {
data.collectables.filter {
searchText.isEmpty ? true : $0.text.localizedCaseInsensitiveContains(searchText)
}
}
}
struct SearchableSubview : View {
#Environment(\.isSearching) private var isSearching
#Binding var selectedItem : Int
var body: some View {
if isSearching {
Picker("Search by", selection: $selectedItem) {
Text("Choice 1").tag(0)
Text("Choice 2").tag(1)
}.pickerStyle(.segmented)
}
}
}

Related

Selecting an existing item on an array or passing a new one to a .sheet

I have an array that contains the data that is displayed on a list. When the user hits "new", a sheet pops up to allow the user to enter a new item to the list.
I just added a swipe option to edit this item and I wanted to reuse the same sheet to edit the item's text. But I'm having problems understanding how to check whether a specific item was selected (by UUID?) to pass to the sheet, or it's a new item.
Code:
let dateFormatter = DateFormatter()
struct NoteItem: Codable, Hashable, Identifiable {
let id: UUID
var text: String
var date = Date()
var dateText: String {
dateFormatter.dateFormat = "EEEE, MMM d yyyy, h:mm a"
return dateFormatter.string(from: date)
}
var tags: [String] = []
}
struct ContentView: View {
#EnvironmentObject private var data: DataModel
#State private var selectedItemId: UUID?
#State var searchText: String = ""
#State private var sheetIsShowing = false
NavigationView {
List(filteredNotes) { note in
VStack(alignment: .leading) {
//....
// not relevant code
}
.swipeActions(allowsFullSwipe: false) {
Button(action: {
selectedItemId = note.id
self.sheetIsShowing = true
} ) {
Label("Edit", systemImage: "pencil")
}
}
}
.toolbar {
// new item
Button(action: {
self.sheetIsShowing = true
}) {
Image(systemName: "square.and.pencil")
}
}
.sheet(isPresented: $sheetIsShowing) {
if self.selectedItemId == NULL { // <-- this is giving me an error
let Note = NoteItem(id: UUID(), text: "New Note", date: Date(), tags: [])
SheetView(isVisible: self.$sheetIsShowing, note: Note)
} else {
let index = data.notes.firstIndex(of: selectedItemId)
SheetView(isVisible: self.$sheetIsShowing, note: data.notes[index])
}
}
}
}
My rationale was to check whether self.selectedItemId == NULL was null or not, if not then pass that element to the sheet to be edited, if yes, the as it as a new element.
What am I doing wrong? And if there is a standard way to pass information to the sheet based on whether there is an item select or not, could you show me?
Thanks!
From this post, you can do like this in your case:
struct SheetForNewAndEdit: View {
#EnvironmentObject private var data: DataModel
#State var searchText: String = ""
// The selected row
#State var selectedNote: NoteItem? = nil
#State private var sheetNewNote = false
// for test :
#State private var filteredNotes: [NoteItem] = [
NoteItem(id: UUID(), text: "111"),
NoteItem(id: UUID(), text: "222")];
var body: some View {
NavigationView {
List(filteredNotes) { note in
VStack(alignment: .leading) {
//....
// not relevant code
Text(note.text)
}
.swipeActions(allowsFullSwipe: false) {
Button(action: {
// the action select the note to display
selectedNote = note
} ) {
Label("Edit", systemImage: "pencil")
}
}
}
// sheet is displayed depending on selected note
.sheet(item: $selectedNote, content: {
note in
SheetView(note: note)
})
// moved tool bar one level (inside navigation view)
.toolbar {
// Toolbar item to have toolbar
ToolbarItemGroup(placement: .navigationBarTrailing) {
ZStack {
Button(action: {
// change bool value
self.sheetNewNote.toggle()
}) {
Image(systemName: "square.and.pencil")
}
}
}
}
.sheet(isPresented: $sheetNewNote) {
let Note = NoteItem(id: UUID(), text: "New Note", date: Date(), tags: [])
SheetView(note: Note)
}
}
}
}
Note : SheetView does not need any more a boolean, but you can add one if you orefer
Swift uses nil, not null, so the compiler is complaining when you are comparing selected items to null. However, you will have another issue. Your selectedItemId is optional, so you can't just use it in your else clause to make your note. You are better off using an if let to unwrap it. Change it to:
.sheet(isPresented: $sheetIsShowing) {
if let selectedItemId = selectedItemId,
let index = data.notes.firstIndex(where: { $0.id == selectedItemId }) {
SheetView(isVisible: self.$sheetIsShowing, note: data.notes[index])
} else {
let note = NoteItem(id: UUID(), text: "New Note", date: Date(), tags: [])
SheetView(isVisible: self.$sheetIsShowing, note: note)
}
}
edit:
I realized that you were attempting to use two optionals without unwrapping them, so I changed this to an if let to make sure both are safely unwrapped.

Crash while dismissing a view that hasn't been edited - SwiftUI

I'm building an iOS app with SwiftUI. When I click the "done" button, and the entry property is not nil, and I have not used the DatePicker TextField or TextView, I get the following runtime error in AppDelegate:
Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffee2a83fe8)
Here is my code:
import SwiftUI
struct EditView: View {
#State var entry: Entry?
#ObservedObject var entries: Entries
#State var newDate: Date
#State var newTitle: String
#State var newBody: String
#Environment(\.presentationMode) var presentationMode
init(entries: Entries, entry: Entry?) {
UIScrollView.appearance().keyboardDismissMode = .onDrag
_entry = .init(initialValue: entry)
_entries = .init(initialValue: entries)
_newDate = .init(initialValue: entry?.date ?? Date())
_newTitle = .init(initialValue: entry?.title ?? "")
_newBody = .init(initialValue: entry?.body ?? "")
}
var body: some View {
GeometryReader { geometry in
Form {
Section {
DatePicker("Date", selection: self.$newDate, in: ...Date(), displayedComponents: .date)
.labelsHidden()
}
Section {
TextField("Title (optional)", text: self.$newTitle)
TextView(placeholder: "Entry", text: self.$newBody)
.frame(width: geometry.size.width, height: 250, alignment: .topLeading)
}
}
}
.navigationBarItems(trailing:
Button("Done") {
if let entry = self.entry {
if let index = self.entries.list.firstIndex(of: entry) {
self.entries.list[index] = Entry(date: self.newDate, title: self.newTitle, body: self.newBody)
}
} else {
self.entries.list.append(Entry(date: self.newDate, title: self.newTitle, body: self.newBody))
}
self.presentationMode.wrappedValue.dismiss()
})
}
}
import Foundation
class Entries: ObservableObject {
#Published var list = [Entry]()
}
class Entry: ObservableObject, Identifiable, Equatable {
static func == (lhs: Entry, rhs: Entry) -> Bool {
return lhs.id == rhs.id
}
let id = UUID()
#Published var date: Date
var dateString: String {
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .none
return formatter.string(from: self.date)
}
#Published var title: String
#Published var body: String
init(date: Date, title: String, body: String) {
self.date = date
self.title = title
self.body = body
}
static let example = Entry(date: Date(), title: "I wrote some swift today", body: "Today I wrote some swift for an app I'm developing. It was very fun.")
When I remove the self.presentationMode.wrappedValue.dismiss() line, the problem goes away. Though, I need that line to dismiss the view. Why would this be happening, and how can I fix it? Please forgive me if my code is a complete mess. Thank you!
It looks like it tries to update during dismissing, try to postpone dismiss a bit
DispatchQueue.main.async { // defer to next event
self.presentationMode.wrappedValue.dismiss()
}

How to automatically collapse DatePicker in a form when other field is being edited?

I got a simple SwiftUI view:
import SwiftUI
struct AddItemView: View {
#State private var title = ""
#State private var date = Date()
var body: some View {
Form {
Section {
TextField("Title", text: $title)
DatePicker(
selection: $date,
in: Date()...,
displayedComponents: .date,
label: { Text("Date") }
)
}
}
}
}
struct AddItemView_Previews: PreviewProvider {
static var previews: some View {
AddItemView()
}
}
I am trying to achieve the following:
If DatePicker is expanded (user tapped date picker, picker showing wheel to select date) and then starts typing text in TextField, DatePicker should automatically switch to initial, minimized mode (just showing label and selected date). Please take a look at screenshot. This is a behaviour in a stock Calendar.app, for example, when creating events.
Any help appreciated, thank you.
Here is possible approach. The idea is to reset DatePicker component for each of events result in editing.
Tested with Xcode 11.4 / iOS 13.4
struct AddItemView: View {
#State private var title = ""
#State private var date = Date()
#State private var pickerReset = UUID()
var body: some View {
Form {
Section {
TitleTextField()
DatePicker(
selection: $date,
in: Date()...,
displayedComponents: .date,
label: { Text("Date") }
).id(self.pickerReset)
}
}
}
private func TitleTextField() -> some View {
let boundText = Binding<String>(
get: { self.title },
set: { self.title = $0; self.pickerReset = UUID() }
)
return TextField("Title", text: boundText, onEditingChanged: { editing in
if editing {
self.pickerReset = UUID()
}
})
}
}

List reload animation glitches

So I have a list that changes when user fill in search keyword, and when there is no result, all the cells collapse and somehow they would fly over to the first section which looks ugly. Is there an error in my code or is this an expected SwiftUI behavior? Thanks.
import SwiftUI
struct ContentView: View {
#ObservedObject var viewModel = ViewModel(photoLibraryService: PhotoLibraryService.shared)
var body: some View {
NavigationView {
List {
Section {
TextField("Enter Album Name", text: $viewModel.searchText)
}
Section {
if viewModel.libraryAlbums.count > 0 {
ForEach(viewModel.libraryAlbums) { libraryAlbum -> Text in
let title = libraryAlbum.assetCollection.localizedTitle ?? "Album"
return Text(title)
}
}
}
}.listStyle(GroupedListStyle())
.navigationBarTitle(
Text("Albums")
).navigationBarItems(trailing: Button("Add Album", action: {
PhotoLibraryService.shared.createAlbum(withTitle: "New Album \(Int.random(in: 1...100))")
}))
}.animation(.default)
}
}
1) you have to use some debouncing to reduce the needs to refresh the list, while typing in the search field
2) disable animation of rows
The second is the hardest part. the trick is to force recreate some View by setting its id.
Here is code of simple app (to be able to test this ideas)
import SwiftUI
import Combine
class Model: ObservableObject {
#Published var text: String = ""
#Published var debouncedText: String = ""
#Published var data = ["art", "audience", "association", "attitude", "ambition", "assistance", "awareness", "apartment", "artisan", "airport", "atmosphere", "actor", "army", "attention", "agreement", "application", "agency", "article", "affair", "apple", "argument", "analysis", "appearance", "assumption", "arrival", "assistant", "addition", "accident", "appointment", "advice", "ability", "alcohol", "anxiety", "ad", "activity"].map(DataRow.init)
var filtered: [DataRow] {
data.filter { (row) -> Bool in
row.txt.lowercased().hasPrefix(debouncedText.lowercased())
}
}
var id: UUID {
UUID()
}
private var store = Set<AnyCancellable>()
init(delay: Double) {
$text
.debounce(for: .seconds(delay), scheduler: RunLoop.main)
.sink { [weak self] (s) in
self?.debouncedText = s
}.store(in: &store)
}
}
struct DataRow: Identifiable {
let id = UUID()
let txt: String
init(_ txt: String) {
self.txt = txt
}
}
struct ContentView: View {
#ObservedObject var search = Model(delay: 0.5)
var body: some View {
NavigationView {
VStack(alignment: .leading) {
TextField("filter", text: $search.text)
.padding(.vertical)
.padding(.horizontal)
List(search.filtered) { (e) in
Text(e.txt)
}.id(search.id)
}.navigationBarTitle("Navigation")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
and i am happy with the result

SwiftUI Picker in a Form doesn't show the selected row

I am trying to have a Picker that shows which option is currently selected.
Try out the following code which correctly selects the right option but the picker does not show which option is selected:
import SwiftUI
struct ContentView: View {
#State var selectedIndex: Int = 0
let strings: [String] = {
var strings: [String] = []
for i in 0..<10 {
strings.append("\(i)")
}
return strings
}()
var body: some View {
NavigationView {
VStack {
Form {
Picker(selection: $selectedIndex,
label: Text("Selected string: \(strings[selectedIndex])")) {
ForEach(0..<strings.count) {
Text(self.strings[$0]).tag($0)
}
}
}
}
.navigationBarTitle("Form Picker",
displayMode: NavigationBarItem.TitleDisplayMode.inline)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Anyone know what could be wrong? It's observed using Xcode 11.1 and iOS 13.1
I created the simple picker I call "ListPicker" which should fit the bill. I've written it so it works well in a Form; if you need it outside of a Form you will have to tinker with it. If you see any way to improve the code, please add a comment; this is still a learning experience for all of us.
// MARK: - LIST PICKER (PUBLIC)
struct ListPicker<Content: View>: View {
#Binding var selectedItem: Int
var label: () -> Content
var data: [Any]
var selectedLabel: String {
selectedItem >= 0 ? "\(data[selectedItem])" : ""
}
var body: some View {
NavigationLink(destination: ListPickerContent(selectedItem: self.$selectedItem, data: self.data)) {
ListPickerLabel(label: self.label, value: "\(self.selectedLabel)")
}
}
}
// MARK: - INTERNAL
private struct ListPickerLabel<Content: View>: View {
let label: () -> Content
let value: String
var body: some View {
HStack(alignment: .center) {
self.label()
Spacer()
Text(value)
.padding(.leading, 8)
}
}
}
private struct ListPickerContentItem: View {
let label: String
let index: Int
let isSelected: Bool
var body: some View {
HStack {
Text(label)
Spacer()
if isSelected {
Image(systemName: "checkmark")
.foregroundColor(.accentColor)
}
}.background(Color.white) // so the entire row is selectable
}
}
private struct ListPickerContent: View {
#Environment(\.presentationMode) var presentationMode
#Binding var selectedItem: Int
var data: [Any]
var body: some View {
List {
ForEach(0..<data.count) { index in
ListPickerContentItem(label: "\(self.data[index])", index: index, isSelected: index == self.selectedItem).onTapGesture {
self.selectedItem = index
self.presentationMode.wrappedValue.dismiss()
}
}
}
}
}
Then you can use it like this:
#State var selectedCar: Int = 0
let cars = ["Jaguar", "Audi", "BMW", "Land Rover"]
Form {
ListPicker(
selectedItem: self.$selectedCar,
label: {
Text("Cars")
},
data: self.cars
)
}

Resources