In my code, I do this:
Text("\(languagesManager.availableWords.count)")
And next time I build, this creates an entry in Localizable.strings: %lld
Is there a way I can flag this UI element to indicate its string doesn't need to be localized?
Post
Replies
Boosts
Views
Activity
For my app I've created a Dictionary that I want to persist using AppStorage
In order to be able to do this, I added RawRepresentable conformance for my specific type of Dictionary. (see code below)
typealias ScriptPickers = [Language: Bool]
extension ScriptPickers: @retroactive RawRepresentable where Key == Language, Value == Bool {
public init?(rawValue: String) {
guard let data = rawValue.data(using: .utf8),
let result = try? JSONDecoder().decode(ScriptPickers.self, from: data)
else {
return nil
}
self = result
}
public var rawValue: String {
guard let data = try? JSONEncoder().encode(self), // data is Data type
let result = String(data: data, encoding: .utf8) // coerce NSData to String
else {
return "{}" // empty Dictionary represented as String
}
return result
}
}
public enum Language: String, Codable, {
case en = "en"
case fr = "fr"
case ja = "ja"
case ko = "ko"
case hr = "hr"
case de = "de"
}
This all works fine in my app, however trying to run any tests, the build fails with the following:
Conflicting conformance of 'Dictionary<Key, Value>' to protocol 'RawRepresentable'; there cannot be more than one conformance, even with different conditional bounds
But then when I comment out my RawRepresentable implementation, I get the following error when attempting to run tests:
Value of type 'ScriptPickers' (aka 'Dictionary<Language, Bool>') has no member 'rawValue'
I hope Joseph Heller is out there somewhere chuckling at my predicament
any/all ideas greatly appreciated
I have a CoreImage pipeline and one of my steps is to rotate my image about the origin (bottom left corner) and then translate it. I'm not seeing the behaviour I'm expecting, and I think my problem is in how I'm combining these two steps.
As an example, I start with an identity transform
(lldb) po transform333
▿ CGAffineTransform
- a : 1.0
- b : 0.0
- c : 0.0
- d : 1.0
- tx : 0.0
- ty : 0.0
I then rotate 1.57 radians (approx. 90 degrees, CCW)
transform333 = transform333.rotated(by: 1.57)
- a : 0.0007963267107332633
- b : 0.9999996829318346
- c : -0.9999996829318346
- d : 0.0007963267107332633
- tx : 0.0
- ty : 0.0
I understand the current contents of the transform.
But then I translate by 10, 10:
(lldb) po transform333.translatedBy(x: 10, y: 10)
- a : 0.0007963267107332633
- b : 0.9999996829318346
- c : -0.9999996829318346
- d : 0.0007963267107332633
- tx : -9.992033562211013
- ty : 10.007960096425679
I was expecting tx and ty to be 10 and 10.
I have noticed that when I reverse the order of these operations, the transform contents look correct. So I'll most likely just perform the steps in what feels to me like the incorrect order.
Is anyone willing/able to point me to an explanation of why the steps I'm performing are giving me these results?
thanks,
mike
I must be missing something here. I want to put a landscape image in a geometry reader that contains a ZStack that contains an image and an overlay centred on top of the Image.
I would like the ZStack and GeoReader's sizes to be the size of Image. (ie I want geometry.size to be the size of the image, which can be used to control the offset of the overlay's position.)
Unfortunately the ZStack also includes the space above the image (ie the top safeArea) and the GeometryReader also includes all the space below the Image. (so geometry.size.height is greater than the height of Image)
I've gone down rabbit holes of adding other items above/below, but I don't seem to be able to prevent the GeometryReader from being vertically greedy.
eg the Text(" ") above the ZStack in the VStack solves the ZStack claiming the top safe area. But adding Text(" ") below the ZStack does not prevent the GeometryReader from claiming more vertical space below the image.
Any/all guidance greatly appreciated.
struct ContentView: View {
var body: some View {
VStack {
// Text(" ")
GeometryReader { geometry in
ZStack {
Image(
uiImage: .init(imageLiteralResourceName: "LandscapeSample")
)
.resizable()
.aspectRatio(contentMode: .fit)
Text("Hello, world!")
.background(.white)
}
.background(.red)
}
.background(.blue)
// Text(" ")
}
}
}
Pretty sure this is a no-no, but asking just in case there's an easy way to make this work
struct DocumentContentView: View {
private static let logger = Logger(
subsystem: "mySubsystem",
category: String(describing: Self.self)
)
var body: some View {
VStack {
Text("Hello")
logger.trace("hello")
}
}
}
This code generates the following compile error at the logger.trace line
buildExpression is unavailable: this expression does not conform to View
I suspect every line of the body var (or any @ViewBuilder - designated code?) needs to 'return' a View. Is this correct? or more importantly any work arounds other than putting some/all of the view contents in a. func()?
In Xcode Version 16.1
Create a new Project, choose Multiplatform, App
For testing system, choose XCTest and UI Tests
In the project, open the newly generated template Unit test file
Click either of the diamonds in the left margin (either to run the example test or the entire file)
Expected Result: Code compiles and then Runs the test/tests
Actual Result: Code compiles, but then never completes testing (the top status bar is stuck saying "Testing..." forever.)
Am I missing something?
Sorry if this question is too vague, however I've tried this multiple times and see the same result. I'm pretty sure I'm doing something wrong, but don't know what.
I have a Multiplatform (iOS and macOS) project that builds, and runs
I add a new target of type Unit Test Bundle
I click the diamond in the margin beside the XCTestCase declaration at the top of the new Test file
The target project builds, then Xcode says 'Testing...' and it stays like this forever.
I've also tried creating a new scheme that targets the target created in the above steps. attempting to run my tests behaves the same. The top status bar will get stuck saying 'Testing...' and never get anywhere.
I'm pretty sure this is something basic.
thanks, in advance for any guidance.
Mike
I have a view containing either a TextField or a SecureField. I'm hoping I can use a single FocusState value that will apply to either the TextField or SecureField. (I'm using FocusState to ensure the cursor will be in the field when it initially loads)
I've verified this works in a sample project when the view is in a WindowGroup. But when I instead use a DocumentGroup ~50% of the time when the view loads/launches, it does not have focus.
Here is my ContentView:
struct ContentView: View {
let coinFlip: Bool = .random() // used to choose between the TextField and the SecureField
@State var fieldContent: String = "" // bound to the Field value
@FocusState var focus: Bool
var body: some View {
VStack {
Text("Coin Flip: \(coinFlip)")
actualField
.focused($focus, equals: true)
}
.onAppear() {
focus = true
}
}
@ViewBuilder var actualField: some View {
if coinFlip {
TextField("Enter text here", text: $fieldContent)
} else {
SecureField("Enter secure text here", text: $fieldContent)
}
}
}
and here is my App swift file
@main
struct ModernTurtleApp: App {
var body: some Scene {
// WindowGroup {
// ContentView()
// }
DocumentGroup(newDocument: ModernTurtleDocument()) { file in
ContentView()
}
}
}
When this code runs, the Field has focus about 50% of the time on initial launch. When I uncomment the WindowGroup and comment the DocumentGroup, the field always has focus on initial launch.
I realize I can work around this behaviour by using an optional enum for FocusState. I would be ok going this route, but I first want to try to understand the behaviour I'm seeing, and possibly keep my simpler FocusState implementation.
Thanks, in advance for any help.
I thought the following code would allow me to have focus in the TextField when the app loads. Is there something else/different that I need to do?
struct ContentView: View {
enum FocusField {
case password
}
@State var fieldContent: String = ""
@FocusState var focus: FocusField?
var body: some View {
VStack {
TextField("Enter text here", text: $fieldContent)
.focused($focus, equals: .password)
Text("Hello, world!")
}
.padding()
.defaultFocus($focus, .password)
}
}
is now broken. (but definitely worked when I originally wrote my Document-based app)
It's been a few years.
DocumentBrowserViewController's delegate implements the following func.
func documentBrowser(_ controller: UIDocumentBrowserViewController, didRequestDocumentCreationWithHandler importHandler: @escaping (URL?, UIDocumentBrowserViewController.ImportMode) -> Void) {
let newDocumentURL: URL? = Bundle.main.url(forResource: "blankFile", withExtension: "trtl2")
// Make sure the importHandler is always called, even if the user cancels the creation request.
if newDocumentURL != nil {
importHandler(newDocumentURL, .copy)
} else {
importHandler(nil, .none)
}
}
When I tap the + in the DocumentBrowserView, the above delegate func is called (my breakpoint gets hit and I can step through the code) newDocumentURL is getting defined successfully and
importHandler(newDocumentURL, .copy)
gets called, but returns the following error:
Optional(Error Domain=com.apple.DocumentManager Code=2 "No location available to save “blankFile.trtl2”." UserInfo={NSLocalizedDescription=No location available to save “blankFile.trtl2”., NSLocalizedRecoverySuggestion=Enable at least one location to be able to save documents.})
This feels like something new I need to set up in the plist, but so far haven't been able to discover what it is.
perhaps I need to update something in info.plist? perhaps one of:
CFBundleDocumentTypes
UTExportedTypeDeclarations
Any guidance appreciated.
thanks :-)
I've created a UserDefaults extension to generate custom bindings.
extension UserDefaults {
func boolBinding(for defaultsKey: String) -> Binding<Bool> {
return Binding (
get: { return self.bool(forKey: defaultsKey) },
set: { newValue in
self.setValue(newValue, forKey: defaultsKey)
})
}
func cardPileBinding(for defaultsKey: String) -> Binding<CardPile> {
return Binding (
get: { let rawValue = self.object(forKey: defaultsKey) as? String ?? ""
return CardPile(rawValue: rawValue) ?? .allRandom
},
set: { newValue in
self.setValue(newValue.rawValue, forKey: defaultsKey)
})
}
}
For the sake of completeness, here is my enum
enum CardPile: String, CaseIterable {
case allRandom
case numbers
case numbersRandom
case daysMonths
case daysMonthsRandom
}
I've also created UI elements that use these bindings:
var body: some View {
VStack {
Toggle("Enable", isOn: UserDefaults.standard.boolBinding(for: "enable"))
Picker("Card Pile", selection: UserDefaults.standard.cardPileBinding(for: "cardPile")) {
ForEach(CardPile.allCases,
id: \.self) {
Text("\($0.rawValue)")
.tag($0.rawValue)
}
}
}
}
When I tap the toggle, it updates correctly. However when I tap the picker and select a different value, the binding setter gets called, but the view does not refreshed to reflect the change in value. (If I force quit the app and re-run it, the I see the change.)
I would like to find out why the Binding works as I'd expected (ie updates the UI when the value changes) but the Binding behaves differently.
any/all guidance very much appreciated.
Note: I get the same behavior when the enum use Int as its rawValue
From what I've read, @AppStorage vars should be @Published, however the following code generates a syntax error at extended's .sink modifier: Cannot call value of non-function type 'Binding<Subject>'
class LanguageManager: ObservableObject {
@Published var fred = "Fred"
@AppStorage("extended") var extended: Bool = true
private var subscriptions = Set<AnyCancellable>()
init() {
$fred
.sink(receiveValue: {value in
print("value: \(value)")
})
.store(in: &subscriptions)
$extended
.sink(receiveValue: {value in
print("value: \(value)")
})
.store(in: &subscriptions)
}
Does anyone know of a way to listen for (subscribe to) changes in @AppStorage values?
didSet works in for a specific subset of value changes, but this is not sufficient for my intended use.
I've defined a value stored in UserDefaults.
In a view struct I have code that can successfully update the stored value.
I've also added an @AppStorage var in an instance of a class, that can read this value and run business logic that depends on the current stored value.
But what I really want to do, is have code in my class that gets automatically called when the value stored in UserDefaults gets updated.
Basically I want to do this:
@AppStorage("languageChoice") var languageChoice: LanguageChoice = .all {
didSet {
print("hello")
}
}
Unfortunately didSet closures in @AppStorage vars do not appear to get called :-(
My clumsy attempts to use combine have all ended in tears from the compiler.
Any/all suggestions are greatly appreciated.
thanks,
Mike
I have a singleton instance of a class that (among other things) is managing which subset of words will be available to users.
The contents of availableWords will always be a subset of words and is always a function of three userDefaults that are bound to user settings (using @AppStorage)
I could dynamically reconstruct availableWords every time it is needed, but it will be read much more frequently than it changes. Because of this, I want to cache the updated list every time a user changes one of the settings that will change its contents.
But the only way I can see to do this is to create an update function and rely on the UI code to call the function any time a user updates one of the settings that will require availableWords to be updated. And this feels more like something out of UIKit.
Do any of you see a better way of managing the updates of availableWords?
class WordsManager {
static let shared = WordsManager()
let words: Words // defined in init
var availableWords: Words // updated anytime scriptPickers, languageChoice or cardPile changes
@AppStorage("scriptPickers") var scriptPickers: ScriptPickers = ScriptPickers.defaultDictionary
@AppStorage("languageChoice") var languageChoice: LanguageChoice = .all
@AppStorage("cardPile") var cardPile: CardPile = .allRandom
func updateAvailableWords() {
var result = words.filtered(by: cardPile.wordList)
let askIdentifiers = languageChoice.askLanguages
let answerIdentifiers = languageChoice.answerLanguages
result = result.matching(askIdentifiers: askIdentifiers, answerIdentifiers: answerIdentifiers)
self.availableWords = result
}
// other stuff
}
In V 0.1 of my app, I went with a simple option for a piece of business logic in my app.
I then changed something else that caused my simplified business logic to now crash the app at startup.
Excellent, a chance to use Test. Driven Design to replace my flawed business logic.
So I wrote my first test TDD test, but when I tried to run the test... It doesn't run because running the test target seems to start by actually running my full app (which as I described in chapter 1 is currently crashing)
Have I configured something incorrectly? or is it normal that when I attempt to run a single test, step 1 is running the full app?
(note: it is very easy for me to disable/avoid the business logic causing my crash. This question is more about my lack of understanding of what it means to run a test target.)
thanks in advance for any and all responses.
Mike