我想在选择器中的某些文本旁边使用图像,但图像已放大,我无法使用 .ressized .frame 和 ... 调整其大小。 我该如何解决这个问题?我同时使用 svg 和 png 格式,但它们都无法正常工作。
我使用资产中的图像
struct ContentView: View {
@State var array = ["one", "two", "three", "four"]
@State var selection: String = "one"
var body: some View {
HStack {
Picker("Select",selection: $selection) {
ForEach(array, id: \.self) { item in
HStack {
Text(item)
Image("BTC")
.resizable()
.clipped()
}
}
}
.pickerStyle(.menu)
.padding(.trailing)
}
}
}
如果您使用旧样式的选择器菜单(即选择新页面而不是弹出菜单),则不会发生此行为。 我认为这是新的 ios 16 行为的一个错误。
尝试将此应用到您的选择器:
.pickerStyle(.navigationLink)
您可以使用
Menu
来实现此目的:
struct ContentView: View {
@State var array = ["one", "two", "three", "four"]
@State var selection: String = "one"
var body: some View {
Menu(content: {
Picker("Select",selection: $selection) {
ForEach(array, id: \.self) { item in
HStack {
Text(item)
Image("BTC")
}
}
}
}, label: {
Text(selection)
})
}
}
对于任何正在寻找 macOS(应用程序套件) 解决方案的人。
import Foundation
import AppKit
extension NSImage {
func scalePreservingAspectRatio(targetSize: NSSize) -> NSImage {
let widthRatio = targetSize.width / size.width
let heightRatio = targetSize.height / size.height
let scaleFactor = min(widthRatio, heightRatio)
let scaledImageSize = NSSize(
width: size.width * scaleFactor,
height: size.height * scaleFactor
)
let newImage = NSImage(size: scaledImageSize)
newImage.lockFocus()
self.draw(
in: NSRect(origin: .zero, size: scaledImageSize),
from: NSRect(origin: .zero, size: self.size),
operation: .copy,
fraction: 1.0
)
newImage.unlockFocus()
return newImage
}
}
import SwiftUI
/// Image resized to a specific size
struct ResizedImage: View {
let resourceName: String
let width: Int
let height: Int
init(_ resourceName: String, width: Int, height: Int) {
self.resourceName = resourceName
self.width = width
self.height = height
}
var body: some View {
if let image = NSImage(named: resourceName) {
let imageResized = image.scalePreservingAspectRatio(targetSize: NSSize(width: 20, height: 20))
Image(nsImage: imageResized)
} else {
// Default questionmark if image is not found
Image(systemName: "questionmark.square")
}
}
}