Again, I have a vertical stack of horizontal stacks of buttons as follows.
import SwiftUI
struct ContentView: View {
		@State private var eventPresented = Bool()
		@State private var selectedEventIndex = Int()
		@State private var monthSelection = Int()
		
		var body: some View {
				VStack {
						VStack(spacing: 0.0) {
								HStack(spacing: 0.0) {
										ForEach((0...6), id: \.self) {
												index in
												Button(buttonTitles[index] ?? "") {
														eventPresented = true
														selectedEventIndex = index + 1 - self.weekIndex
												}
												.foregroundColor(titleColors[index])
												.overlay(Text(eventNumbers[index] ?? "").font(.footnote).foregroundColor(.blue).offset(x: -16, y: -16))
												.buttonStyle(BorderlessButtonStyle())
												.frame(width: 48, height: 48, alignment: .center)
												.background(RoundedRectangle(cornerRadius: 2)
																				.fill(fillColors[index])
																				.shadow(color: shadowColors[index], radius: 2, x: 0, y: 0)
												)
												.sheet(isPresented: $eventPresented) {
														EventView(eventVisible: self.$eventPresented, dayFromParent: self.$selectedEventIndex, monthFromParent: self.$monthSelection)
												}
										}
								}
								...
								...
								HStack(alignment: .top, spacing: 0.0) {
										ForEach((35...36), id: \.self) {
												index in
												Button(buttonTitles[index] ?? "") {
														eventPresented = true
														selectedEventIndex = index + 1 - self.weekIndex
												}
												.foregroundColor(titleColors[index])
												.overlay(Text(eventNumbers[index] ?? "").font(.footnote).foregroundColor(.blue).offset(x: -16, y: -16))
												.buttonStyle(BorderlessButtonStyle())
												.frame(width: 48, height: 48, alignment: .center)
												.background(RoundedRectangle(cornerRadius: 2)
																				.fill(fillColors[index])
																				.shadow(color: shadowColors[index], radius: 2, x: 0, y: 0)
												)
												.sheet(isPresented: $eventPresented) {
														EventView(eventVisible: self.$eventPresented, dayFromParent: self.$selectedEventIndex, monthFromParent: self.$monthSelection)
												}
										}
								}
								.frame(width: 336.0, height: 48.0, alignment: .leading)
						}
				}
		}
}
And I want to send a few variables to EventView when the user clicks on a button.
struct EventView: View {
		@Binding var eventVisible: Bool
		@Binding var dayFromParent: Int
		@Binding var monthFromParent: Int
		var body: some View {
				VStack {
						Text("Window sheet.")
						Button("OK") {
								self.eventVisible = false
								print("month from parent: \(monthFromParent)")
								print("day from parent: \(dayFromParent)")
						}
				}
				.frame(width: 240, height: 180)
		}
}
If I just want to send two variables to it,
EventView(eventVisible: self.$eventPresented, dayFromParent: self.$selectedEventIndex)
the compiler didn't complain. For the third variable, it says
SwiftUI the compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions I know what it means. Some say it could resolve the issue by making the data types of variables clearer. Others say you could use a function to return a variable for a somewhat complex algebra equation. But what can I do in my case? Does anybody have any suggestions?
Thank you
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
I've been waiting since I had Organizer sent my latest IPA to iTunes Connect servers 40 minutes ago. But the App Store Connect site doesn't show it. Is anyone having the same issue? I hate it when it happens because you don't know how long you have to wait.
Topic:
App Store Distribution & Marketing
SubTopic:
App Store Connect
I have downloaded a sample project at raywenderlich.com (https://www.raywenderlich.com/22408716-drag-and-drop-editable-lists-tutorial-for-swiftui). I am working on a project involving DropDelegate. And I have a question with this project to make my point.
In reference to the picture shown below, if I grab, drag and move Count Sheep, its preview picture will shrink. How could I prevent the preview picture from shrinking its size?
struct ContentView: View {
@EnvironmentObject private var todoList: TodoList
@State private var isShowingAddTodoView = false
@State private var editMode: EditMode = .inactive
@State private var focusId: Int?
func addTodo() {
isShowingAddTodoView = true
}
var body: some View {
NavigationView {
VStack {
FocusTodoView(focusId: focusId)
.padding()
.onDrop(
of: [TodoItem.typeIdentifier],
delegate: TodoDropDelegate(focusId: $focusId))
ScrollView {
ActiveTodoView()
CompletedTodoView()
.disabled(editMode.isEditing)
.onDrop(of: [TodoItem.typeIdentifier], isTargeted: nil) { itemProviders in
for itemProvider in itemProviders {
itemProvider.loadObject(ofClass: TodoItem.self) { todoItem, _ in
guard let todoItem = todoItem as? TodoItem else { return }
DispatchQueue.main.async {
todoList.updateTodo(withId: todoItem.id, isCompleted: true)
}
}
}
return true
}
}
.applyPlainListAppearance()
.navigationBarTitle("Drag Todo")
.toolbar {
ToolbarItemGroup(placement: .navigationBarTrailing) {
EditButton()
Button(action: addTodo) {
Image(systemName: "plus")
}
.disabled(editMode.isEditing)
}
}
.environment(\.editMode, $editMode)
.sheet(isPresented: $isShowingAddTodoView) {
AddTodoView()
}
}
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
I wish I had a simpler sample. That's the only sample I have been able to find. Anyway, I've been asking Google all day about "SwiftUI DropDelegate preview" with no luck. Thanks.
In Cocoa, you can find out whether or not you have a Retina screen with the backingScaleFactor property like the following.
func getWinFactor() -> CGFloat? {
if let view = self.view.window {
let factor = view.backingScaleFactor
return factor
} else {
return nil
}
}
How could we detect whether or not the application is dealing with a Retina screen in SwiftUI? I thought the displayScale Environment property is the chosen one. But my 27-inch iMac with a Retina display will return the scale as 1.0.
import SwiftUI
struct ContentView: View {
@Environment(\.displayScale) var displayScale
var body: some View {
VStack {
...
}
.onAppear {
print("display scale: \(displayScale)") // Returning 1.0
}
}
}
Do I miss something with this environment guy? Muchos thankos.
I have created a simple calendar framework of my own. The screenshot below shows what it looks like.
The following lines show a concise version of my calendar framework. The deal is such that the app will return a date when I tap a date button with the callBack closure.
import SwiftUI
struct ContentView: View {
@State private var navigateToAddDate = false
@State private var days: [Day] = []
@State var callBack: ((Date) -> Void)
private let cols = [
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible())
]
var body: some View {
NavigationStack {
VStack {
LazyVGrid(columns: cols) {
ForEach(days, id: \.self) { day in
Button(action: {
selectedDay = day
navigateToAddDate.toggle()
}, label: {
Image(systemName: "\(day.num).circle.fill")
.resizable()
.aspectRatio(contentMode: .fit)
.foregroundColor(day.show ? dateTextForecolor(day: day) : .clear)
})
.disabled(day.isInvalid)
}
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var callBack: (Date) -> Void = { _ in }
static var previews: some View {
ContentView(callBack: callBack)
}
}
struct Day: Hashable {
let date: Date
let text: String
let num: Int
let dayOfWeek: Int
let show: Bool
let isInvalid: Bool
}
Well, PreviewProvider works. Now, I want to use #Preview that comes with iPhone 15.
#Preview {
var callBack: (Date) -> Void = { _ in }
ContentView(callBack: callBack)
}
And I get a warning and an error. The warning is the following
Result of 'ContentView' initializer is unused
, which seems to stem from the said warning. How can I make the Preview guy work? Thanks.
I have gone through several tutorials for WeatherKit. But my sample app doesn't return weather data. The following is a list of what I have.
I've registered a Bundle ID for my sample app with the WeatherKit capability on.
I've created a developer profile for my sample app.
I've opened my Xcode project to make sure that the WeatherKit capability is enabled.
I have run my sample app with an actual device.
I have waited for more than 30 minutes for the service to kick in. It's been several days.
The following is my code.
import SwiftUI
import CoreLocation
import WeatherKit
struct ContentView: View {
@State var currentWeather: CurrentWeather?
var body: some View {
NavigationStack {
List {
Group {
SampleCell(title: "Temperature", value: String(currentWeather?.apparentTemperature.value ?? 0.0) + "℃")
SampleCell(title: "Cloud coverage", value: String(currentWeather?.cloudCover ?? 0.0))
SampleCell(title: "Weather condition", value: String(currentWeather?.condition.description ?? ""))
SampleCell(title: "Dew point", value: String(currentWeather?.dewPoint.value ?? 0.0) + "℃")
SampleCell(title: "Humidity", value: String(currentWeather?.humidity ?? 0.0))
SampleCell(title: "Pressure", value: String(currentWeather?.pressure.value ?? 0.0) + "mbar")
SampleCell(title: "Pressure trend", value: String(currentWeather?.pressureTrend.description ?? ""))
SampleCell(title: "Temperature", value: String(currentWeather?.temperature.value ?? 0.0) + "℃")
SampleCell(title: "UV index", value: String(currentWeather?.uvIndex.value ?? 0))
SampleCell(title: "Visibility", value: String(currentWeather?.visibility.value ?? 0.0) + "m")
}
SampleCell(title: "Window direction", value: String(currentWeather?.wind.direction.value ?? 0.0) + "°")
SampleCell(title: "Window speed", value: String(currentWeather?.wind.speed.value ?? 0.0) + "km/h")
SampleCell(title: "Gust", value: String(currentWeather?.wind.gust?.value ?? 0.0) + "km/h")
}
.navigationTitle(Text("CurrentWeather"))
.task {
let service = WeatherService()
let location = CLLocation(
latitude: 35.467081,
longitude: 139.620798
)
do {
let weather = try await service.weather(for: location)
currentWeather = weather.currentWeather
} catch let error {
print(error.localizedDescription)
}
}
}
}
}
struct SampleCell: View {
var title: String
var value: String
var body: some View {
VStack {
HStack {
Text(title)
Spacer()
Text(value)
}
}
}
}
Yet, I constantly get the following warnings.
2023-11-29 09:33:46.504737+0900 WeatherCrazyMama[15279:9734572] [WeatherDataService] Aborting silent interpolation: no interpolator object; location=CLLocationCoordinate2D(latitude: 35.467081, longitude: 139.620798)
2023-11-29 09:33:47.900605+0900 WeatherCrazyMama[15279:9734577] [AuthService] Failed to generate jwt token for: com.apple.weatherkit.authservice with error: Error Domain=WeatherDaemon.WDSJWTAuthenticatorServiceListener.Errors Code=2 "(null)"
2023-11-29 09:33:47.989603+0900 WeatherCrazyMama[15279:9734572] [WeatherService] Encountered an error when fetching weather data subset; location=<+35.46708100,+139.62079800> +/- 0.00m (speed -1.00 mps / course -1.00) @ 2023/11/29 9:33:46 AM Japan Standard Time, error=WeatherDaemon.WDSJWTAuthenticatorServiceListener.Errors 2 Error Domain=WeatherDaemon.WDSJWTAuthenticatorServiceListener.Errors Code=2 "(null)"
The operation couldn’t be completed. (WeatherDaemon.WDSJWTAuthenticatorServiceListener.Errors error 2.)
What am I doing wrong? Thanks.
I have an NSStatusBar application. This is my first in SwiftUI. And I need to know when the window is closed so that I can disable some of menu commands. I can use NSWindowDelegate with AppDelegate as follows.
import SwiftUI
@main
struct SomeApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
@StateObject private var menuViewModel = MenuViewModel()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(menuViewModel)
}
}
}
class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {
private var menuViewModel = MenuViewModel()
func applicationDidFinishLaunching(_ notification: Notification) {
if let window = NSApplication.shared.windows.first {
window.setIsVisible(false)
window.delegate = self
}
}
func windowWillClose(_ notification: Notification) {
menuViewModel.windowClosed = true
}
}
When the window will close, MenuViewModel (ObservableObject) will receive a call, which I want my ContentView to receive. But, so far, it won't.
import SwiftUI
struct ContentView: View {
var body: some View {
ZStack {
...
...
}
.onReceive(statusBarViewModel.$windowClosed) { result in
// never called...
}
}
}
Can a SwiftUI View receive a call somehow when its window closes? Muchos thankos.
I have several vertical stacks of six horizontal buttons. And I want to open a modal sheet based on the button they click on.
import SwiftUI
struct ContentView: View {
		@State private var eventPresented = false
		@State private var selectedEventIndex = 3
		
		@State var shadowColors: [Color] = Array(repeating: Color.clear, count: 38)
		@State var titleColors: [Color] = Array(repeating: Color.black, count: 38)
		@State var fillColors: [Color] = Array(repeating: Color.clear, count: 38)
		@State var buttonTitles: [String?] = Array(repeating: nil, count: 38)
		@State var eventNumbers: [String?] = Array(repeating: nil, count: 38)
		
		var body: some View {
				VStack {
						VStack(spacing: 0.0) {
								HStack(spacing: 0.0) {
										ForEach((0...6), id: \.self) {
												Button(buttonTitles[$0] ?? "") {
														eventPresented = true
														selectedEventIndex = 5 // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
												}
												.foregroundColor(titleColors[$0])
												.overlay(Text(eventNumbers[$0] ?? "").font(.footnote).foregroundColor(.blue).offset(x: -16, y: -16))
												.buttonStyle(BorderlessButtonStyle())
												.frame(width: 48, height: 48, alignment: .center)
												.background(RoundedRectangle(cornerRadius: 2)
																				.fill(fillColors[$0])
																				.shadow(color: shadowColors[$0], radius: 2, x: 0, y: 0)
												)
												.sheet(isPresented: $eventPresented) {
														EventView(eventVisible: self.$eventPresented, valueFromParent: self.$selectedEventIndex)
												}
										}
								}
								...
								...
								...
								HStack(alignment: .top, spacing: 0.0) {
										ForEach((35...36), id: \.self) {
												Button(buttonTitles[$0] ?? "") {
														eventPresented = true
														selectedEventIndex = 5
												}
												.foregroundColor(titleColors[$0])
												.overlay(Text(eventNumbers[$0] ?? "").font(.footnote).foregroundColor(.blue).offset(x: -16, y: -16))
												.buttonStyle(BorderlessButtonStyle())
												.frame(width: 48, height: 48, alignment: .center)
												.background(RoundedRectangle(cornerRadius: 2)
																				.fill(fillColors[$0])
																				.shadow(color: shadowColors[$0], radius: 2, x: 0, y: 0)
												)
												.sheet(isPresented: $eventPresented) {
														EventView(eventVisible: self.$eventPresented, valueFromParent: self.$selectedEventIndex)
												}
										}
								}
								.frame(width: 336.0, height: 48.0, alignment: .leading)
						}
				}
		}
}
struct EventView: View {
		@Binding var eventVisible: Bool
		@Binding var valueFromParent : Int
		var body: some View {
				VStack {
						Text("This is a sheet.")
						Button("OK") {
								self.eventVisible = false
								print("From parent: \(valueFromParent)")
						}
				}
				.frame(width: 240, height: 180)
		}
}
For now, I arbitrarily set eventPresented to 5, which will be passed to EventView. How can I set $0 to this state value like
eventPresented = $0
Thank you.
I have a SwiftUI desktop application. And I need to open a window sheet from a storyboard with a click of a button, which works. But I have a problem.
The opening window sheet is very big. Its size is 1,400 x 300 pixels. (I don't know the exact height.) I don't know where this size comes from. But I need to make it smaller. If I try to do it with the view controller, it doesn't work. How can I control the opening window sheet size?
// SwiftUI View //
import SwiftUI
struct ContentView: View {
		@State private var sheetPresented = false
		@State private var selectionIndex = 3
		
		var body: some View {
				ZStack {
						VStack {
								Button(action: {
										sheetPresented = true
								}) {
										Text("Show me a sheet")
								}
								.sheet(isPresented: $sheetPresented) {
										SheetViewControllerRepresentation(message: String(selectionIndex))
								}
						}
				}.frame(minWidth: 360, idealWidth: 360, maxWidth: 360, minHeight: 240, idealHeight: 240, maxHeight: 240, alignment: .center)
		}
}
// View controller //
import Cocoa
import SwiftUI
class SheetViewController: NSViewController {
		// MARK: -
		var message = String()
				
		// MARK: - IBOutlet
		@IBOutlet weak var messageLabel: NSTextField!
		// MARK: - IBAction		
		@IBAction func closeClicked(_ sender: NSButton) {
				/* closing window */
				self.view.window?.setIsVisible(false)
				self.view.window?.close()
		}
		// MARK: - Life cycle
		override func viewDidLoad() {
				super.viewDidLoad()
				// Do view setup here.
		}
		
		override func viewWillAppear() {
				super.viewWillAppear()
				
				messageLabel.stringValue = message
		}
		
		override func viewDidAppear() {
				super.viewDidAppear()
				
				view.setFrameSize(CGSize(width: 320, height: 220))
		}
}
struct SheetViewControllerRepresentation: NSViewControllerRepresentable {
		var message = String()
		
		func makeNSViewController(context: NSViewControllerRepresentableContext<SheetViewControllerRepresentation>) -> SheetViewController {
				let mainStoryboard = NSStoryboard(name: "Main", bundle: nil)
				let sheetViewController = mainStoryboard.instantiateController(withIdentifier: "SheetView") as! SheetViewController
				sheetViewController.message = self.message
				return sheetViewController
		}
		
		func updateNSViewController(_ nsViewController: SheetViewController, context: NSViewControllerRepresentableContext<SheetViewControllerRepresentation>) {
		}
}
Thank you.
Hello. I'm a little bit confused about how TestFlight works. If I have an iOS app under development that has not been in the store and that has not been submitted for a review yet, can I use TestFlight to have it tested by my development team? I know that there are two types of tests, internal tests and external tests. It seems that you can use TestFlight for internal tests even if the app has not been submitted for a review. Thanks.
I have the following lines of code in practicing Combine.
import UIKit
import Combine
class ViewController: UIViewController {
// MARK: - Variables
var cancellable: AnyCancellable?
@Published var segmentNumber: Int = 0
// MARK: - IBOutlet
@IBOutlet weak var actionButton: UIButton!
// MARK: - IBAction
@IBAction func segmentChanged(_ sender: UISegmentedControl) {
segmentNumber = sender.selectedSegmentIndex
}
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
cancellable = $segmentNumber.receive(on: DispatchQueue.main)
.assign(to: \.isEnabled, on: actionButton)
}
}
I get an error at .assign that says
Value of type 'UIView?' has no member 'isEnabled'
What am I doing wrong? Thank you.
I'm trying to understand how Combine works. The following is my sample code.
import UIKit
import Combine
class ViewController: UIViewController {
// MARK: - Variables
var cancellable: AnyCancellable?
// MARK: - IBAction
@IBAction func buttonTapped(_ sender: UIButton) {
currentValueSubject.send(20)
}
// MARK: - Life cycle
var currentValueSubject = CurrentValueSubject<Int, Never>(1)
override func viewDidLoad() {
super.viewDidLoad()
let cancellable = currentValueSubject
.sink { value in
print("New value: \(value)")
}
currentValueSubject.send(5)
currentValueSubject.send(10)
//currentValueSubject.send(completion: .finished)
currentValueSubject.send(15)
//cancellable.cancel()
}
}
If I run it with the iPhone simulator, I get
New value: 1
New value: 5
New value: 10
New value: 15
If I tap the button, the app won't get a new value. I suppose that's because the subscription is cancelled at the end of viewDidLoad? If so, why does it get cancelled? I don't quite see a practical side of Combine's Subject. When is it useful? Thanks.
I just want to show a simple navigation title like the following.
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
ZStack {
Color.red.edgesIgnoringSafeArea(.all)
Text("Hello")
}
.navigationTitle("GGG")
.navigationBarTitleDisplayMode(.inline)
.navigationBarHidden(false)
}
}
}
And I get a bunch of mumbo jumbo auto-layout warnings (Unable to simultaneously satisfy constraints...) in Console. If I comment out the navigationTitle line, I won't get them. I have never seen those messages in showing a navigation title when writing code with UIKit. What am I doing wrong? Muchos thankos
I have the following lines of code to work with a list of strings.
import SwiftUI
struct ContentView: View {
@State private var users = ["George", "Kenny", "Susan", "Natalie"]
var body: some View {
NavigationView {
List {
ForEach(users, id: \.self) { user in
Text(user)
}
.onDelete(perform: delete)
}
.navigationBarTitle("My family")
.toolbar {
EditButton()
}
}
}
func delete(at offsets: IndexSet) {
users.remove(atOffsets: offsets)
}
}
Now, I'm doing the following out of curiosity. Now, I have a button in naviationBarItems. And I wonder if I can turn on and off the edit feature of the list with the button?
struct ContentView: View {
@State private var users = ["George", "Kenny", "Susan", "Natalie"]
var body: some View {
NavigationView {
List {
ForEach(users, id: \.self) { user in
Text(user)
}
}
.navigationBarTitle("My family")
.navigationBarItems(trailing:
Button(action: {
print("Edit button pressed...")
}) {
Text("Edit")
}
)
}
}
}
Muchos thankos.
I have the following lines of code for showing a list of friends.
import SwiftUI
struct ContentView: View {
@State var users = ["Susan", "Kate", "Natalie", "Kimberly", "Taylor", "Sarah", "Nancy", "Katherine", "Nicole", "Linda", "Jane", "Mary", "Olivia", "Barbara"]
@State var editMode = EditMode.inactive
var body: some View {
NavigationView {
List {
ForEach(users, id: \.self) { user in
Text(user)
}
}
.navigationBarTitle("Friends")
.environment(\.editMode, $editMode)
.navigationBarItems(leading: Button("Edit", action: {
if self.editMode == .active {
self.editMode = .inactive
} else {
self.editMode = .active
}
}))
}
}
}
If you see the code at the bottom, I have four lines just in order to change the value of editMode. Does SwiftUI have something like
showDetails.toggle()
where showDetails is a Boolean variable? Muchos thankos.