我有一个分享按钮,应该分享一个表情包(图像+顶部文本+底部文本)。下面是关于这个按钮的代码:
Button(
action: {
items.removeAll()
items.append(createImage(from: UIHostingController(rootView: Meme(image: image, topText: topText, bottomText: bottomText)).view))
showingSharePage = true
}
) {
Image(systemName: "square.and.arrow.up")
.font(.title)
}如您所见,我将要共享的项目附加到项目中。我分享的是一个使用UIView生成的UIImage,该函数具有以下功能:
func createImage(from view: UIView) -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(width: view.frame.width, height: view.frame.height), true, 1)
view.layer.render(in: UIGraphicsGetCurrentContext()!)
let generatedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return generatedImage!
}但是,当我在模拟器或设备本身上运行时,我在"view.layer.render( in : UIGraphicsGetCurrentContext()!)“这一行中得到了这样的错误:"Fatal error: Unexpectedly nil when unwrapping an Optional value!”在createImage函数中。
这是我的meme结构:
struct Meme: View {
@State var image: Image?
@State var topText: String
@State var bottomText: String
var body: some View {
image!
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: UIScreen.main.bounds.size.width)
.overlay(
TextField("TOP", text: $topText)
.foregroundColor(.white)
.font(Font.custom("HelveticaNeue-CondensedBlack", size: 30))
.frame(width: UIScreen.main.bounds.size.width * 0.75)
.multilineTextAlignment(.center)
.padding(.vertical, 50.0)
.onTapGesture {
topText = ""
},
alignment: .top
)
.overlay(
TextField("BOTTOM", text: $bottomText)
.foregroundColor(.white)
.font(Font.custom("HelveticaNeue-CondensedBlack", size: 30))
.frame(width: UIScreen.main.bounds.size.width * 0.75)
.multilineTextAlignment(.center)
.padding(.vertical, 50.0)
.onTapGesture {
bottomText = ""
},
alignment: .bottom
)
}
}你知道为什么它返回nil吗?
发布于 2021-07-28 21:29:55
有趣的是,问题出在以下几行中
UIHostingController(rootView: Meme(image: image, topText: topText, bottomText: bottomText)).view)和
UIGraphicsBeginImageContextWithOptions(CGSize(width: view.frame.width, height: view.frame.height), true, 1)令我惊讶的是,UIHostingViewController返回的视图的初始框架是CGRect.zero
所以你实际上是在告诉上下文有一个0的点大小,显然它只是默默地失败了。可以通过在createImage:函数中打印大小来再次检查这一点
print(view.frame)或
print(view.frame.size)我很确定这就是问题所在。
https://stackoverflow.com/questions/68550512
复制相似问题