I like to to know if we could count or some mathematic inside ForEach, here is my code, I want get count of A and B after finishing ForEach loop. Is it possible?
struct ContentView: View {
#State var appData: [String] = ["A", "B", "A", "A", "B"]
var body: some View {
ForEach(appData, id: \.self) { item in
Text(item)
.font(.title)
.bold()
.foregroundColor(item == "A" ? Color.red : Color.blue)
}
Text("Count of A: ")
Text("Count of B: ")
}
}
You can declare two computed properties outside the body:
var aCount: Int {
appData
.filter { $0 == "A" }
.count
}
var bCount: Int {
appData
.filter { $0 == "B" }
.count
}
and then. use them inside like this:
Text("Count of A: \(aCount)")
Text("Count of B: \(bCount)")
struct ContentView: View {
#State var appData: [String] = ["A", "B", "A", "A", "B"]
var body: some View {
ForEach(appData, id: \.self) { item in
let Calculation = 1 + 2
return Text(item)
.font(.title)
.bold()
.foregroundColor(item == "A" ? Color.red : Color.blue)
}
Text("Count of A: ")
Text("Count of B: ")
}
}
Related
I am using in swiftUI. When select picker, it is not changing. Here is code..
Here is datamodel:
struct SourceAccountModel:Codable,Identifiable{
var id: Int
let accountNumber: String
let accountTitle: String
let priaryAccount: String
init(id:Int=0,accountNumber: String, accountTitle: String, priaryAccount: String) {
self.id = id
self.accountNumber = accountNumber
self.accountTitle = accountTitle
self.priaryAccount = priaryAccount
}
}
Here is my code
struct Test2: View {
#State private var selectedOption = "Option 1"
#State private var sourceAccountList = [SourceAccountModel]()
var body: some View {
VStack{
ZStack {
RoundedRectangle(cornerRadius: 8)
.fill(Color.white)
.shadow(radius: 2)
Picker(selection: $selectedOption,label: EmptyView()) {
ForEach (0..<sourceAccountList.count,id: \.self) {
Text(sourceAccountList[$0].accountNumber)
}
}
.padding(8)
}
.frame(maxWidth: .infinity)
}.onAppear{
intitializeValue()
}
}
func intitializeValue(){
self.sourceAccountList.append(SourceAccountModel(id:1,accountNumber: "Option 1", accountTitle: "", priaryAccount: ""))
self.sourceAccountList.append(SourceAccountModel(id:2,accountNumber: "Option 2", accountTitle: "", priaryAccount: ""))
}
}
Always select first value. What is the wrong with my code?
selectedOption is a String, but your ForEach iterates over Range<Int>.
You can fix this by changing selectedOption to Int, e.g.
#State private var selectedOption = 0
You might find it easier to store the actual object in selectedOption: SourceAccountModel, iterate over the sourceAccountList, and tag each row:
struct SourceAccountModel: Identifiable, Hashable {
let id: Int
let accountNumber: String
init(id: Int, accountNumber: String) {
self.id = id
self.accountNumber = accountNumber
}
}
struct ContentView: View {
init() {
let sourceAccountList = [SourceAccountModel(id: 1, accountNumber: "Option 1"),
SourceAccountModel(id: 2, accountNumber: "Option 2")]
_sourceAccountList = State(wrappedValue: sourceAccountList)
_selectedOption = State(wrappedValue: sourceAccountList[0])
}
#State private var selectedOption: SourceAccountModel
#State private var sourceAccountList = [SourceAccountModel]()
var body: some View {
VStack {
Picker("Select", selection: $selectedOption) {
ForEach(sourceAccountList) { model in
Text(model.accountNumber).tag(model)
}
}
}
}
}
How do I do text wrapping?
Here is my code:
struct ContentView: View {
private let items: [String] = [
"OneLineLongggggggggggggggggggggggggggggggggggggggggg",
"TwoLinesLonggggggggggggg\nLongggggggggggggggg",
"ThreeLinesLonggggggggggggg\nLongggggggggggggggg\nLongggggggggggggggg"
]
#State private var text: String = ""
var body: some View {
VStack {
Picker("Select Text", selection: self.$text) {
ForEach(self.items, id: \.self) {
Text($0)
.tag($0)
}
}
Text("select: \(self.text)")
}
}
}
Here is the result:
If I add fixSize then the elements run over each other:
struct ContentView: View {
private let items: [String] = [
"OneLineLongggggggggggggggggggggggggggggggggggggggggg",
"TwoLinesLonggggggggggggg\nLongggggggggggggggg",
"ThreeLinesLonggggggggggggg\nLongggggggggggggggg\nLongggggggggggggggg"
]
#State private var text: String = ""
var body: some View {
VStack {
Picker("Select Text", selection: self.$text) {
ForEach(self.items, id: \.self) {
Text($0)
.tag($0)
.fixedSize(horizontal: false, vertical: true)
}
}
Text("select: \(self.text)")
}
}
}
Here is the result:
Please tell me in which direction to look for the answer?
Please use .lineLimit(any number of max lines you want) with text.
In this case you can use
Text($0)
.tag($0)
.lineLimit(3)
This is the code :
struct ContentView: View {
#State var names = ["A" , "B", "C", "D"]
var body: some View {
List {
ForEach(names, id: \.self ) { name in
Group {
testStruct(name: name)
}
}.onDelete(perform: removeItems)
}
}
private func removeItems (indexSet: IndexSet) {
names.remove(atOffsets: indexSet)
}
}
struct testStruct: View , Identifiable {
#State var name: String
let id = UUID()
var body: some View {
HStack {
Text(name)
Spacer()
Image(systemName: "folder.fill")
}
}
}
I am unable to remove the trailing red animation on swiping onDelete . Is there any elegant way of doing that . .animation() seem not to be working
i would like to remove the space between my back button ("Rezept hinzufügen") and my navigationbarTitle ("Suche")... I cant figure out why this space is there so i need your swarm intelligence. :)
What did i try?
Working with a ZStack, maybe there is NavigationView from before which is doin this bug
Add Spacer()
Recreate the whole view
Now I stuck...
I think the easiest way is to show you my problem with an video...
Here you can see my problem
Here is my code...
import SwiftUI
extension UIApplication
{
func endEditing(_force : Bool)
{
self.windows
.filter{$0.isKeyWindow}
.first?
.endEditing(_force)
}
}
struct ResignKeyboardOnDragGesture: ViewModifier
{
var gesture = DragGesture().onChanged{_ in UIApplication.shared.endEditing(_force: true)}
func body(content: Content) -> some View
{
content.gesture(gesture)
}
}
extension View
{
func resignKeyboardOnDragGesture() -> some View
{
return modifier(ResignKeyboardOnDragGesture())
}
}
/*
Zutaten pflegen Button, zum hinzufügen von Zutaten zu einem Rezept.
**/
struct RecipeIngredientsView: View {
let myArray = ["Dennis", "Tessa", "Peter", "Anna", "Tessa", "Klaus", "Xyan", "Zuhau", "Clown", "Brot", "Bauer"]
#State private var searchText = ""
#State private var showCancelButton: Bool = false
var body: some View {
NavigationView
{
VStack
{
HStack
{
HStack
{
Image(systemName: "magnifyingglass")
TextField("Suche", text: $searchText, onEditingChanged: { isEditing in self.showCancelButton = true}, onCommit: {
print("onCommit")
}).foregroundColor(.primary)
Button(action: {
self.searchText = searchText
}){
Image(systemName: "xmark.circle.fill").opacity(searchText == "" ? 0 : 1)
}
}.padding(EdgeInsets(top: 8, leading: 6, bottom: 8, trailing: 6))
.foregroundColor(.secondary)
.background(Color(.secondarySystemBackground))
.cornerRadius(10.0)
if showCancelButton {
Button("Abbrechen")
{
UIApplication.shared.endEditing(_force: true)
self.searchText = ""
self.showCancelButton = false
}
.foregroundColor(Color(.systemBlue))
}
}
.padding(.horizontal)
.navigationBarHidden(showCancelButton)
//Gefilterte Liste der Namen aus meinem Array
List {
ForEach(myArray.filter{$0.hasPrefix(searchText) || searchText == ""}, id:\.self)
{
searchText in Text(searchText)
}
}
.navigationBarTitle(Text("Suche"))
.resignKeyboardOnDragGesture()
}
}
}
}
Thanks for your help!
:-)
Just remove redundant NavigationView - it is needed only one in same view hierarchy, and obviously there is already some in parent view
struct RecipeIngredientsView: View {
let myArray = ["Dennis", "Tessa", "Peter", "Anna", "Tessa", "Klaus", "Xyan", "Zuhau", "Clown", "Brot", "Bauer"]
#State private var searchText = ""
#State private var showCancelButton: Bool = false
var body: some View {
NavigationView // << remove this one !!
{
I'm coding my app in SwiftUI, and am trying to follow their declarative conventions but I'm coming a little unstuck.
I have a data model which is passed down through the view hierarchy using Bindings, and one of my child views has the ability to change a few of the properties on the Model to trigger a layout change.
Because its animations are a function of the data, I need to stagger the change to the model to get the animation I want. Here's a simple example; assume I need to clear the contents of the child view for architectural reasons. What's the best way to get the content to draw in to the red panel before ChildView animates up, and then when dismissed, wait until the animation is finished before removing the content?
struct ContentView: View {
#State var contents: [String] = ["A", "B", "C", "A", "B", "C", "A", "B", "C"]
#State var showingPanel: Bool = false
var body: some View {
VStack {
HStack {
Button(action: {
self.contents = ["A", "B", "C", "A", "B", "C", "A", "B", "C"]
self.showingPanel = true
}) {
Text("Show Panel")
}
Button(action: {
self.showingPanel = false
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.contents = []
}
}) {
Text("Clear Panel")
}
}
ChildView(showingPanel: $showingPanel, contents: $contents)
}
}
}
struct ChildView: View {
#Binding var showingPanel: Bool
#Binding var contents: [String]
var body: some View {
ZStack {
Color.red
VStack {
ForEach(contents, id: \.self) { content in
Text(content).font(.title)
}
}.animation(nil)
}.offset(y: showingPanel ? 0 : UIScreen.main.bounds.size.height).animation(.default)
}
}
My first stab was to use the DispatchQueue to try and delay the change, but that doesn't look right and also doesn't work!