【发布时间】:2021-07-28 21:29:54
【问题描述】:
我有一个分享按钮,应该分享一个模因(图像 + 顶部文本 + 底部文本)。这是有关此按钮的代码:
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!
}
但是当我在模拟器或设备本身上运行时,我收到此错误:“致命错误:在展开可选值时意外发现 nil”在“view.layer.render(in: UIGraphicsGetCurrentContext()! )" 在 createImage 函数中。
这是我的模因结构:
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 吗?
【问题讨论】: