I am a newbie and i have been attempting to construct a safari app extension as my first venture.
I am attempting to customise the look of NavigationLink rows inside a listing when pressed.
Proper now, urgent every row seems to be like this:
It will get that darkish grey spotlight, and that i need to change it to one thing smoother.
The code for that view is split in two information, the HomeView and the FolderRowView. I am going to add each for context:
// HomeView snippet
var physique: some View {
NavigationStack {
VStack(alignment: .main, spacing: 8) {
HStack {
Textual content("Discover")
.font(.title2)
Spacer()
SortButton(isAscending: $isAscending) // Now correctly updates sorting
}
SearchBar(textual content: $searchText)
.padding(.vertical, 2)
//under is the record with the NavigationLink
Record(filteredFolders) { folder in
NavigationLink(vacation spot: DummyFolderDetailView(folder: folder)) {
FolderRowView(folder: folder)
}
}
.clipShape(RoundedRectangle(cornerRadius: 8))
.navigationTitle("Folders")
}
}
}
// Element FolderRowView
struct FolderRowView: View {
let folder: Folder
@State personal var isHovering = false
var physique: some View {
HStack {
// Folder Icon
Picture(systemName: "folder.fill")
.resizable()
.scaledToFit()
.body(width: 18, peak: 18)
.foregroundStyle(.grey)
Spacer()
// Folder Title
Textual content(folder.title)
.font(.physique)
.body(maxWidth: .infinity, alignment: .main)
// Chevron Icon
Picture(systemName: "chevron.proper")
.foregroundColor(.grey)
}
.padding(.vertical, 6)
.padding(.horizontal, 10) // Added horizontal padding for area round content material
.background(isHovering ? Colour.grey.opacity(0.1) : Colour.clear) // Non-obligatory background change on hover
.scaleEffect(isHovering ? 1.05 : 1.0) // Zoom-in impact
.cornerRadius(8)
.animation(.easeInOut(period: 0.2), worth: isHovering) // Clean animation
.onHover { hovering in
isHovering = hovering
}
.contextMenu { //(...)
In order you possibly can see i already efficiently added on hover styling and animation to the rows by working contained in the element file.
I understand that customizing the on press type is a little more sophisticated than that!
I attempted:
.onTapGesture with @State personal var isPressed = false within the element file, which confirmed up on press accurately, however interfered with the NavigationLink click on in a means the motion was now not actioning 🙂
Made a 3rd element file CustomStyle containing view struct PressableStyle: ButtonStyle that was then added as a modifier to the NavigationLink as .buttonStyle(PressableStyle()) but it surely did not actually do something..
ChatGPT steered i attempt making a element view FolderRowLink that calls the FolderRowView, nests it inside a button, and embeds a hidden NavigationLink triggered by the button. Then within the HomeView i would solely should name that FolderRowLink view within the record. I attempted this but it surely has the identical end result as the primary strategy, the place the brand new on press type exhibits up however clicking would not motion.
I perceive the spotlight colour utilized by default within the on press is the accentColor, however i’ve bumped into some points with it the place .foregroundStyle(.accent) calls my Belongings.xcassets AccentColor, however .foregroundStyle(Colour.accentColor) calls a darkish grey (the one exhibiting on press by default) and including type modifiers to the NavigationLink would not work both.
Total i assume i simply need to know whether or not styling that is attainable, and the way do you guys do it?
As somebody who combines a lifelong ardour for speculative fiction with rigorous experience in vitality programs and the analytical lens of an English literature pupil, I strategy Erik Rakhou’s Touching Hydrogen Future (2022) and Jeremy Rifkin’s The Hydrogen Financial system (2002) with each fascination and deep skepticism. Seen by this twin lens—as literary hypothesis relatively than credible roadmaps—their narratives develop into attention-grabbing but essentially simplistic visions of a future constructed upon hydrogen. Evaluation reveals how each authors, maybe as a result of their penchant for imaginative and fantastical storytelling, dramatically oversimplify the real-world complexities of technological transitions, neglecting essential socio-economic, moral, and geopolitical dimensions that extra refined science fiction handles explicitly.
Jeremy Rifkin’s The Hydrogen Financial system (2002) positions hydrogen as one thing akin to an alchemist’s thinker’s stone, a legendary substance that guarantees easy transformation from carbon-heavy society to hydrogen-powered abundance. Rifkin presents hydrogen not merely as a helpful vitality vector, however as an almost magical common solvent that dissolves the issues of fossil gas dependency with out significant resistance or consequence. This optimism, whereas interesting, aligns intently with the golden-age speculative fiction custom—boldly imaginative, but typically divorced from the friction-filled actuality of technological and infrastructural transitions.
As a aspect notice, I spoke at a convention final yr simply earlier than Rifkin, positing a probably scifi world of full electrification, but one rather more primarily based in actuality.
20 years later, Erik Rakhou’s Touching Hydrogen Future continues this custom of non-pragmatic techno-utopianism. Rakhou offers narratives spanning a number of sectors—transportation, trade, home heating, and worldwide vitality commerce—all powered easily and seamlessly by hydrogen. In his imagined future, hydrogen integration throughout the globe happens nearly effortlessly, with negligible consideration of the huge financial prices, complicated infrastructure calls for, and profound societal shifts required.
Exploring particular envisioned functions by the lens of science fiction, which is what each books actually are, reveals the essential limitations and simplifications in these hydrogen narratives:
Each Rifkin and Rakhou enthusiastically think about hydrogen fueling the whole lot from private vehicles to maritime ships and transcontinental airplanes, as simply as warp-drive know-how propels starships in Star Trek. In Gene Roddenberry’s universe, the Starship Enterprise effortlessly travels huge distances powered by dilithium crystals and warp cores, not often encountering useful resource or infrastructural friction. But, even inside this optimistic future, Star Trek addresses the complexities of technological development explicitly, acknowledging useful resource shortage, diplomatic challenges, and moral dilemmas surrounding know-how use. Rifkin and Rakhou, conversely, disregard these nuanced realities. They current hydrogen-powered transport as universally viable with out addressing the immense challenges and inefficiencies related to hydrogen infrastructure—storage tanks, fueling stations, and distribution logistics—points that intently parallel the monumental, costly, and resource-intensive effort required to construct the Galactic Empire’s Demise Star in Star Wars. Just like the Demise Star, hydrogen infrastructure requires huge investments, central management, and comes with inherent vulnerabilities, but Rifkin and Rakhou neglect these realities.
Rifkin and Rakhou equally painting hydrogen as effortlessly revolutionizing heavy industries, corresponding to metal and chemical manufacturing, akin to the easy materials transformations made doable by the replicators in Star Trek. Replicators provide immediate abundance with out seen financial or societal disruption—but, crucially, Star Trek usually explores the socio-economic penalties of technological abundance, discussing potential impacts on labor markets, human function, and moral frameworks. Rifkin’s and Rakhou’s portrayal misses these essential dimensions fully, suggesting that industrial transitions happen with out financial dislocation, workforce retraining, or vital infrastructure improvement. The imagined industrial hydrogen transition is portrayed like Starfleet’s replicator know-how: immediate, flawless, friction-free—however with out the wealthy narrative consideration Star Trek constantly offers round such highly effective know-how.
Each authors current hydrogen as a easy, universally obtainable buffer for intermittent renewable vitality, a seamless storage medium akin to the near-infinite, easy management depicted by the magical Pressure in Star Wars. Nevertheless, in actuality, managing energy era by hydrogen storage includes vital vitality losses, sophisticated distribution networks, and appreciable financial prices. The Pressure, as depicted in Star Wars, seems limitless and common but requires self-discipline, coaching, and steadiness—classes Rifkin and Rakhou neglect fully of their portrayal of hydrogen as a simple answer to renewable intermittency. Their simplified eventualities overlook the essential intricacies of constructing and managing environment friendly, dependable vitality programs, inadvertently implying that hydrogen can magically steadiness renewables with out financial or infrastructural friction.
Hydrogen’s use for residence heating and home vitality consumption in Rifkin’s and Rakhou’s visions mirrors the plentiful vitality availability aboard the Enterprise in Star Trek, the place vitality appears endlessly obtainable at minimal price and most comfort. Nevertheless, constructing hydrogen infrastructure into properties includes substantial retrofitting, vital prices, and raises essential security issues ignored by each authors. In distinction, renewables like rooftop photo voltaic and localized vitality options embody the scrappy resilience and decentralized adaptability of the Insurgent Alliance—inexpensive, versatile, and attentive to native wants, creating a much more resilient, community-driven vitality future.
A considerably deeper literary perspective reveals the distinction between Rifkin’s and Rakhou’s simplified utopian narratives and the subtle, complicated vitality explorations present in Iain M. Banks’ acclaimed sequence, The Tradition. Banks’ fictional civilization depends on hyper-intelligent synthetic intelligences (Minds) to handle complicated socio-economic programs, moral questions, and governance. These Minds, analogous to clever grid administration and adaptive infrastructure, embody the kind of considerate complexity fully absent in Rifkin’s and Rakhou’s simplistic depictions. Banks demonstrates that real technological development requires clever, adaptable governance—issues hydrogen proponents too typically neglect.
Likewise, Star Trek’s humanist strategy constantly questions the societal affect and moral penalties of know-how. In contrast to Rifkin and Rakhou, who not often handle societal disruption, Star Trek explicitly highlights how technological developments necessitate cautious consideration of fairness, moral governance, and inclusive societal restructuring.
Star Wars additional amplifies this critique, highlighting how centralized technological tasks—such because the Empire’s Demise Star—typically symbolize vulnerability, dominance, and oppression. Hydrogen’s huge infrastructure calls for, centralized management, and susceptibility to catastrophic failure intently parallel the Empire’s mannequin. Renewables, represented metaphorically by the Insurgent Alliance, emphasize decentralization, resilience, adaptability, and native management—qualities that foster equitable and sustainable vitality programs.
Rifkin’s The Hydrogen Financial system and Rakhou’s Touching Hydrogen Future successfully perform as imaginative, speculative narratives however essentially fail as real looking blueprints for precise vitality transitions. Actual-world vitality transformations require nuanced understanding, clever governance, socio-economic adaptability, and moral foresight—components central to stylish speculative fiction from Banks and Roddenberry. Readers and policymakers alike ought to strategy Rifkin’s and Rakhou’s hydrogen utopias critically, maybe having fun with their imaginative worth whereas sustaining a clear-eyed recognition of the profound complexity inherent in real vitality transitions.
Essentially Rifkin’s and Rakhou’s books are dangerous science fiction, however sadly each have develop into influential within the try and create their simplistic and inefficient visions. They need to be handled like L. Ron Hubbard’s science fiction, with disdain and ten foot poles.
When a keyboard is proven, the presenting view will transfer backwards if the detent is taller than maxDetentValue - keyboardHeight, so that you want a detent that could be a little bit shorter than that.
It is in all probability secure to make this a static nonisolated(unsafe) var too if you might want to assist earlier variations. I extremely doubt top(for:) will ever be known as from someplace apart from the principle actor, for the reason that corresponding UIKit API is fundamental actor remoted.
Use it like this:
.presentationDetents([.fraction(0.1), .fraction(0.333), .custom(CustomDetent.self)], choice: $selectedDetent)
.onChange(of: isSearchFocused) {_, targeted in
if targeted {
selectedDetent = .customized(CustomDetent.self)
}
}
You then arrange some publishers to watch the keyboard (from this reply):
extension Publishers {
static var keyboardHeight: AnyPublisher {
let willShow = NotificationCenter.default.writer(for: UIApplication.keyboardWillShowNotification)
.map { $0.keyboardHeight }
let willHide = NotificationCenter.default.writer(for: UIApplication.keyboardWillHideNotification)
.map { _ in CGFloat(0) }
return MergeMany(willShow, willHide)
.eraseToAnyPublisher()
}
}
extension Notification {
var keyboardHeight: CGFloat {
return (userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect)?.top ?? 0
}
}
You possibly can put an onReceive in your root view:
.onReceive(Publishers.keyboardHeight) { top in
CustomDetent.keyboardHeight.withLock { $0 = top }
}
There he goes once more. The skinny-skinned dictator-adjacent Commander-in-Chief who occupies the Oval Workplace foisted catastrophe upon US farmers when he sparked commerce wars throughout his first time period in workplace, and now the American citizens has empowered him to do it another time. In the meantime, farmers elsewhere across the globe are able to pounce on markets deserted by the US, together with with the assistance of recent agrivoltaic techniques that produce each clear power and crops on the identical land.
Professional tip: Subsequent time, don’t vote for the convicted felon.
Commerce Wars And The Agrivoltaic Answer
President Trump’s first spherical of commerce wars labored out famously for US farmers, and never in a great way. They landed on the dropping finish of the stick in 2018 when China retaliated in opposition to Trump’s new tariffs. The Council on Overseas Relations was amongst these toting up the damages. By October of 2020, CFR calculated that greater than 92% of the tax income from the brand new tariffs went to bail out farmers who suffered lack of export markets as a result of commerce struggle.
“That commerce struggle has value U.S. corporations many billions in new import taxes (whereas undermining their competitiveness and growing shopper costs), but it has earned the federal government far much less,” CFR summarized, noting that Trump’s funds to farmers totaled $61 billion — sure, billion — by 2020.
This time round, Trump is shaping as much as be an excellent worse catastrophe for farmers. Other than the influence of retaliatory tariffs, Trump’s belligerence has motivated non-government boycotts of US foodstuffs to materialize in Canada, for instance.
Trump’s reckless budget-cutting spree is one other issue. US meals producers relying on gross sales to USAID meals help packages have already been battered by steep cuts to the company.
The Trump freeze on federal disbursements is one more monetary disaster within the making. Farmers who contracted for on-site photo voltaic initiatives by way of the Agriculture Division’s REAP mortgage and grant program are left holding the bag for 1000’s of {dollars} invested up entrance.
None of this bodes properly for the up-and-coming agrivoltaic motion within the US. Agrivoltaic techniques symbolize a next-level method to farmland use, by which photo voltaic panels may be deployed strategically to generate electrical energy whereas the farmer continues to make use of the land for pollinator habitats, grazing, and different agricultural actions. The science behind solar-plus-farming is comparatively new, however momentum was starting to take maintain throughout the Biden administration when … oops … oh, properly….
Europe Takes The Lead On Agrivoltaics
Europe has already been implementing agrivoltaic practices at a sooner tempo than the US, and Trump’s reckless funds cuts all however assure the US shall be left behind within the mud for years to return. That’s as a result of European governments proceed to spend money on agrivoltaic analysis initiatives that maximize yields and income from dual-use farming.
One key problem includes enabling farmers to calculate how the income from electrical energy era can offset the lack of farming house wanted for the photo voltaic panels. As well as, though the rising consensus is that photo voltaic panels don’t intrude with grassland productiveness, they do compete for daylight with different crops, so productiveness additionally must be factored into the equation.
A analysis group from Germany’s Fraunhofer Institute for Photo voltaic Vitality Techniques has provide you with a brand new calculating device. The mission focuses on apple orchards, with a watch on serving to Germany obtain its renewable power objectives whereas optimizing apple manufacturing.
The deal with apples is especially instructive as a result of apples require totally different ranges of sunshine for optimum outcomes all through the rising season, from buds to blossom and fruition. The researchers additionally decided that Germany’s longtime expertise in deploying hail-proof nets to guard apple orchards may assist inform their analysis.
Calculating The Steadiness Between Crops And Photo voltaic Vitality
The researchers credit score an thought in circulation since 2011 with forming the premise of their method, which identifies horizontal single-axis monitoring techniques as essentially the most versatile technique of adjusting mild administration all through the rising season. Additionally they observe that a variety of business corporations have already got such techniques up and working in Europe,
The technical particulars can be found on-line on the SPIE digital library underneath the title, “Enhancing agrivoltaic synergies by way of optimized monitoring methods.” In a nutshell, the researchers verify that “horizontal single-axis tracker agrivoltaic techniques can mitigate agricultural yield losses by way of optimized monitoring methods that steadiness mild distribution between crops and photo voltaic panels.”
The authors additionally pay attention to some limitations and challenges of their work. Nonetheless, the research does present agrivoltaic advocates with extra proof that crops and photo voltaic panels can co-exist profitably. Their research confirmed that dynamic photo voltaic panel monitoring may obtain 91% of the focused mild for rising apples over the course of a yr, with only a 20% loss in yield for the photo voltaic panels.
Agrivoltaic Techniques And The Tariff Wars Of The Future
Along with uncooked productiveness, the research authors additionally point out that an optimized agrivoltaic system may be tweaked to enhance the standard of crops. They observe that “mild high quality, depth, and period profoundly have an effect on a variety of agronomic traits, together with fruit ripening, coloration, and general high quality, which in flip affect marketability and shopper preferences.”
That’s a very key consideration in Germany, the place apples are an export crop that accounts for about 70% of all fruit grown domestically. As a facet observe, Germany is so awash in apple peels that researchers are exploring methods to repurpose them for power storage techniques and different cleantech.
The US Apple Affiliation (USAA), for one, was already involved about commerce struggle impacts after Trump concluded his first time period in workplace. In the course of the Biden administration, the group cited “retaliatory tariffs, the shortage of recent commerce agreements and a powerful greenback” among the many elements reducing US apple exports by 25% since 2018. USAA drew specific consideration to the lack of new markets in India and China because of Trump’s commerce wars.
Entry to the European market, USAA identified, has additionally been restricted partly on account of Europe’s pesticide insurance policies. On the time, the group urged Congress to extend funding for the USDA’s Market Entry Program, an identical grant program geared toward selling US apples abroad.
No phrase but on whether or not or not USDA could have the funds, or the workers, to assist US farmers survive the brand new commerce wars, non-government boycotts, the lack of USAID income, and the monetary issues arising from the Trump freeze on USDA disbursements for photo voltaic initiatives.
An agrivoltaic enhance may assist. Trump took the US authorities itself out of the working, however all shouldn’t be misplaced. Preserve a watch out for state-based analysis initiatives geared toward serving to farmers deploy solar energy to remain in enterprise. Over in New York, for instance, researchers are exploring how photo voltaic panels may very well be deployed as an alternative of hail nets to guard a high-density apple orchard the place younger dwarf bushes have been planted.
Picture: The agrivoltaic motion within the US has misplaced momentum underneath the Trump administration, however different international locations proceed to pursue the dual-use monitor for worthwhile, productive farming (courtesy of NREL).
Subject
I’m encountering a difficulty in SwiftUI the place modifying a value-type mannequin inside a baby view typically causes the navigation stack to pop unexpectedly. This occurs though I am solely modifying a property contained in the youngster view, not changing the whole mannequin.
Context
I’ve an inventory of things in a NavigationStack, the place choosing an merchandise navigates to a element view. The element view permits enhancing the title property through a TextField.
Right here’s the simplified code:
import SwiftUI
struct Merchandise: Identifiable, Hashable {
let id: UUID
var title: String
}
struct ContentView: View {
@State non-public var objects = [
Item(id: UUID(), name: "Item 1"),
Item(id: UUID(), name: "Item 2")
]
var physique: some View {
NavigationStack {
Listing($objects) { $merchandise in
NavigationLink(merchandise.title, worth: merchandise)
}
.navigationDestination(for: Merchandise.self) { merchandise in
DetailView(merchandise: merchandise)
}
}
}
}
struct DetailView: View {
@State var merchandise: Merchandise // <- Native copy of the merchandise
var physique: some View {
VStack {
TextField("Edit Title", textual content: $merchandise.title)
.textFieldStyle(.roundedBorder)
.padding()
}
.navigationTitle(merchandise.title)
}
}
Drawback
Once I sort within the TextField, the view typically pops again to the earlier display with out urgent the again button. It looks like the navigation stack is shedding monitor of my Merchandise occasion when its title is up to date.
Used @Binding in DetailView
Modified DetailView to just accept a @Binding var merchandise: Merchandise as a substitute of utilizing @State.
This prompted a compiler error as a result of NavigationDestination passes a copied worth, not a binding.
Wrapped Merchandise in a Reference Kind (class)
Transformed Merchandise from a struct to a category and used @ObservableObject.
This fastened the navigation pop subject however launched issues with Codable, Hashable, and thread security.
Tracked the Chosen Merchandise Individually
Launched an express @State non-public var selectedItem: Merchandise? in ContentView.
Manually assigned the chosen merchandise earlier than navigation.
This labored however felt like a hack moderately than a SwiftUI-friendly strategy.
Anticipated Habits
Updating merchandise.title inside DetailView ought to solely replace that subject and never trigger SwiftUI to pop the navigation stack.
Precise Habits
Altering merchandise.title typically causes the view to pop unexpectedly, as if SwiftUI misplaced monitor of the navigation state.