【发布时间】:2021-03-15 15:28:14
【问题描述】:
我有下面的结构来处理图像选择器,但我无法将选择的图像传递给要显示的视图。下面选择的路径正确打印文件的位置,但是如何将此选定的文件分配给图片到视图中?
struct FileView: View {
var body: some View {
Button("Select File") {
let openPanel = NSOpenPanel()
openPanel.prompt = "Select File"
openPanel.allowsMultipleSelection = false
openPanel.canChooseDirectories = false
openPanel.canCreateDirectories = false
openPanel.canChooseFiles = true
openPanel.allowedFileTypes = ["png","jpg","jpeg"]
openPanel.begin { (result) -> Void in
if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
let selectedPath = openPanel.url!.path
print(selectedPath)
}
}
}
}
}
在我显示所选图像的位置下方:
struct NewPost: View {
@Environment(\.presentationMode) var presentationMode
var postToEdit: Item?
var viewContext: NSManagedObjectContext
...
@State var fileUrl: URL?
var header: String {
postToEdit == nil ? "Create Post" : "Edit Post"
}
var body: some View {
...Form Code
// Displaying Image if its selected...
Section(header: Text("Picture").foregroundColor(Color("blue")).font(.title2)) {
if let fileUrl = fileUrl, let img = NSImage(contentsOf: fileUrl) {
Image(nsImage: img)
.resizable()
.scaledToFill()
.clipShape(Circle())
.overlay(Circle().stroke(Color.white, lineWidth: 1))
.opacity(1)
.frame(minWidth: 120, maxWidth: 120, minHeight: 120, maxHeight: 120)
}
if pic.count != 0 {
Image(nsImage: NSImage(data: pic)!)
.resizable()
.scaledToFill()
.clipShape(Circle())
.overlay(Circle().stroke(Color.white, lineWidth: 1))
.opacity(1)
.frame(minWidth: 120, maxWidth: 120, minHeight: 120, maxHeight: 120)
}
}
.cornerRadius(10)
根据下面的响应更新了上面的代码。
提前致谢。
【问题讨论】:
标签: swift macos swiftui imagepicker