gpt4 book ai didi

UIScrollView in Swift with CanvasView(Swift中的UIScrollView与CanvasView)

转载 作者:bug小助手 更新时间:2023-10-25 15:28:20 25 4
gpt4 key购买 nike



With the following code I create a scrollview for an object which in this case is a Rectangle with a CanvasView on it. My first problem is that when I zoom out the view, the object moves more to the left and no longer stays in the middle. If I zoom in, the scrollView becomes so wide that it takes a long time to reach the edge. So my questions are how to keep the object in the middle and how to reduce the border between my inserted object and the border of the scrollView.

使用下面的代码,我为一个对象创建了一个滚动视图,在本例中,该对象是一个带有Canvas View的矩形。我的第一个问题是,当我缩小视图时,对象会更多地向左移动,而不再停留在中间。如果我放大,滚动视图变得太宽,以至于需要很长时间才能到达边缘。所以我的问题是如何将对象保持在中间,以及如何减少我插入的对象与ScrollView的边框之间的边框。


import SwiftUI

struct ZoomableScrollView<Content: View>: UIViewRepresentable {
@State private var screenHeight: CGFloat = UIScreen.main.bounds.height

private var content: Content

init(@ViewBuilder content: () -> Content) {
self.content = content()
}

func makeUIView(context: Context) -> UIScrollView {
// set up the UIScrollView
let scrollView = UIScrollView()
scrollView.delegate = context.coordinator // for viewForZooming(in:)
scrollView.maximumZoomScale = 20
scrollView.minimumZoomScale = 0.8
scrollView.bouncesZoom = true
// scrollView.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
scrollView.contentMode = .center
scrollView.contentSize = CGSize(width: 200, height: 500)

// create a UIHostingController to hold our SwiftUI content
let hostedView = context.coordinator.hostingController.view!
hostedView.translatesAutoresizingMaskIntoConstraints = true
hostedView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
hostedView.backgroundColor = UIColor(red: 0, green: 1, blue: 0, alpha: 0)
hostedView.contentMode = .center

scrollView.addSubview(hostedView)

return scrollView
}

func makeCoordinator() -> Coordinator {
return Coordinator(hostingController: UIHostingController(rootView: self.content))
}

func updateUIView(_ uiView: UIScrollView, context: Context) {
// update the hosting controller's SwiftUI content
context.coordinator.hostingController.rootView = self.content
assert(context.coordinator.hostingController.view.superview == uiView)
}

// MARK: - Coordinator

class Coordinator: NSObject, UIScrollViewDelegate {
var hostingController: UIHostingController<Content>

init(hostingController: UIHostingController<Content>) {
self.hostingController = hostingController
}

func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return hostingController.view
}
}
}

更多回答
优秀答案推荐
更多回答

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com