SwiftUI 2.0 | 斯威夫特 5.4 | Xcode 12.4 | macOS 大苏尔 11.4
在 iOS 中,有一种方法可以将 SwiftUI 视图渲染为 UIImage,但该方法在 AppKit 中不起作用,仅在 UIKit 中起作用:
extension View {
func snapshot() -> UIImage {
let controller = UIHostingController(rootView: self)
let view = controller.view
let targetSize = controller.view.intrinsicContentSize
view?.bounds = CGRect(origin: .zero, size: targetSize)
view?.backgroundColor = .clear
let renderer = UIGraphicsImageRenderer(size: targetSize)
return renderer.image { _ in
view?.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
}
}
}
Run Code Online (Sandbox Code Playgroud)
有什么解决方法可以让它在 AppKit 上运行吗?该方法UIGraphicsImageRenderer(size:)不适用于 AppKit,并且没有等效方法。
当我使用 SwiftUI App Lifecycle 创建应用程序时,工具栏按钮与新的 Big Sur 工具栏按钮样式(具有 onHover 效果样式)匹配。但是如果我选择传统的 AppDelegate Lifecycle 并通过 Storyboards 自定义工具栏,那么我会得到这个没有 onHover 效果的按钮样式:
该按钮以矩形为背景出现。有谁知道我怎样才能达到新的风格?
SwiftUI、Swift 5.2、Xcode 11.4
我试图观察单身人士的变化,但我并不总是刷新我的 SwiftUI 视图:
final class Patient: ObservableObject {
static var shared: Patient
@Published var medicalData: MedicalData
init { ... }
final class MedicalData {
var allergies: String
var ...
init { ... }
}
}
Run Code Online (Sandbox Code Playgroud)
所以,在我的 SwiftUI 视图中:
struct ContentView: View {
@ObservedObject var patient: Patient = Patient.shared
var body: some view { ... }
}
Run Code Online (Sandbox Code Playgroud)
如果任何对象替换了医疗数据,发布者将正确通知我的 SwiftUI:
patient.medicalData = NEW_MEDICAL_DATA --> OK! View refreshed
Run Code Online (Sandbox Code Playgroud)
但是,如果任何对象更改了当前医疗数据中的值,则不会刷新 SwiftUI 视图:
patient.medicalData.allergies = "Alcanfor" --> NOT PUBLISHED
Run Code Online (Sandbox Code Playgroud)
有谁知道如何做到这一点?先感谢您。
可以这样设置按钮样式吗...?
Button() { }
.buttonStyle(.default)
Run Code Online (Sandbox Code Playgroud)
而不是这个...?
Button() { }
.buttonStyle(DefaultButtonStyle())
Run Code Online (Sandbox Code Playgroud)
我尝试编写扩展代码,但它不起作用。
extension ButtonStyle {
static var `default`: DefaultButtonStyle {
DefaultButtonStyle()
}
}
Run Code Online (Sandbox Code Playgroud)
它说:Static member 'default' cannot be used on protocol metatype 'ButtonStyle.Protocol'
有没有办法.popover()在 SwiftUI 中呈现 macOS 中的动画而无需动画?
Pages 和 Keynote 等应用程序呈现的弹出窗口没有任何动画。我尝试过这个但没有运气:
\nButton() { \n withAnimation(.easeInOut(duration: 0)) {\n popoverPresented.toggle()\n }\n}\nRun Code Online (Sandbox Code Playgroud)\nXcode 12.2 | SwiftUI 2.0 |\xc2\xa0Swift 5.2 | macOS 11.0.1
\n我正在尝试修改此扩展以获得可变性:
extension Collection where Element: Equatable {
/// Returns the element at the specified index iff it is within count, otherwise nil.
subscript (safe index: Index) -> Element? {
indices.contains(index) ? self[index] : nil
}
}
Run Code Online (Sandbox Code Playgroud)
我想实现这个工作:
var array = ["Hello", "World"]
array[safe: 5] = "Other word" // This will not be setted because index is out of bounds, but error won't be throwed.
Run Code Online (Sandbox Code Playgroud)
当我尝试修改下标扩展名时...
extension Collection where Element: Equatable {
/// Returns the element at the specified index iff …Run Code Online (Sandbox Code Playgroud)