- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
最近我一直在尝试创建一个拉到(刷新,加载更多)swiftUI ScrollView !!,灵感来自 https://cocoapods.org/pods/SwiftPullToRefresh
我正在努力获得偏移量和内容的大小。但是现在当用户释放 ScrollView 以完成 UI 时,我正在努力获取事件。
这是我当前的代码:
struct PullToRefresh2: View {
@State var offset : CGPoint = .zero
@State var contentSize : CGSize = .zero
@State var scrollViewRect : CGRect = .zero
@State var items = (0 ..< 50).map { "Item \($0)" }
@State var isTopRefreshing = false
@State var isBottomRefreshing = false
var top : CGFloat {
return self.offset.y
}
private var bottomLocation : CGFloat {
if contentSize.height >= scrollViewRect.height {
return self.contentSize.height + self.top - self.scrollViewRect.height + 32
}
return top + 32
}
private var shouldTopRefresh : Bool {
return self.top > 80
}
private var shouldBottomRefresh : Bool {
return self.bottomLocation < -80 + 32
}
func watchOffset() -> Binding<CGPoint> {
return .init(get: {
return self.offset
},set: {
print("watched : offset= \($0)")
self.offset = $0
})
}
private func computeOffset() -> CGFloat {
if isTopRefreshing {
print("OFFSET: isTopRefreshing")
return 32
} else if isBottomRefreshing {
if (contentSize.height+32) < scrollViewRect.height {
print("OFFSET: isBottomRefreshing 1")
return top
} else if scrollViewRect.height > contentSize.height {
print("OFFSET: isBottomRefreshing 2")
return 32 - (scrollViewRect.height - contentSize.height)
} else {
print("OFFSET: isBottomRefreshing 3")
return scrollViewRect.height - contentSize.height - 32
}
}
print("OFFSET: fall back->\(top)")
return top
}
func watchScrollViewRect() -> Binding<CGRect> {
return .init(get: {
return self.scrollViewRect
},set: {
print("watched : scrollViewRect= \($0)")
self.scrollViewRect = $0
})
}
func watchContentSize() -> Binding<CGSize> {
return .init(get: {
return self.contentSize
},set: {
print("watched : contentSize= \($0)")
self.contentSize = $0
})
}
func newDragGuesture() -> some Gesture {
return DragGesture()
.onChanged { _ in
print("> drag changed")
}
.onEnded { _ in
DispatchQueue.main.async {
print("> drag ended")
self.isTopRefreshing = self.shouldTopRefresh
self.isBottomRefreshing = self.shouldTopRefresh
withAnimation {
self.offset = CGPoint.init(x: self.offset.x, y: self.computeOffset())
}
}
}
}
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View {
VStack {
Button(action: { self.presentationMode.wrappedValue.dismiss() }) {
Text("Back")
}
ZStack {
OffsetScrollView(.vertical, showsIndicators: true,
offset: self.watchOffset(),
contentSize: self.watchContentSize(),
scrollViewFrame: self.watchScrollViewRect())
{
VStack {
ForEach(self.items, id: \.self) { item in
HStack {
Text("\(item)")
.font(.system(Font.TextStyle.title))
.fontWeight(.regular)
//.frame(width: geo.size.width)
//.background(Color.blue)
.padding(.horizontal, 8)
Spacer()
}
//.background(Color.red)
.padding(.bottom, 8)
}
}//.background(Color.clear)
}.edgesIgnoringSafeArea(.horizontal)
.background(Color.red)
//.simultaneousGesture(self.newDragGuesture())
VStack {
ArrowShape()
.stroke(style: StrokeStyle.init(lineWidth: 2, lineCap: .round, lineJoin: .round, miterLimit: 0, dash: [], dashPhase: 0))
.fill(Color.black)
.frame(width: 12, height: 16)
.padding(.all, 2)
//.animation(nil)
.rotationEffect(.degrees(self.shouldTopRefresh ? -180 : 0))
.animation(.linear(duration: 0.2))
.transformEffect(.init(translationX: 0, y: self.top - 32))
.animation(nil)
.opacity(self.isTopRefreshing ? 0 : 1)
Spacer()
ArrowShape()
.stroke(style: StrokeStyle.init(lineWidth: 2, lineCap: .round, lineJoin: .round, miterLimit: 0, dash: [], dashPhase: 0))
.fill(Color.black)
.frame(width: 12, height: 16)
.padding(.all, 2)
//.animation(nil)
.rotationEffect(.degrees(self.shouldBottomRefresh ? 0 : -180))
.animation(.linear(duration: 0.2))
.transformEffect(.init(translationX: 0, y: self.bottomLocation))
.animation(nil)
.opacity(self.isBottomRefreshing ? 0 : 1)
}
// Color.init(.sRGB, white: 0.2, opacity: 0.7)
//
// .simultaneousGesture(self.newDragGuesture())
}
.clipped()
.clipShape(Rectangle())
Text("Offset: \(String(describing: self.offset))")
Text("contentSize: \(String(describing: self.contentSize))")
Text("scrollViewRect: \(String(describing: self.scrollViewRect))")
}
}
}
//https://zacwhite.com/2019/scrollview-content-offsets-swiftui/
public struct OffsetScrollView<Content>: View where Content : View {
/// The content of the scroll view.
public var content: Content
/// The scrollable axes.
///
/// The default is `.vertical`.
public var axes: Axis.Set
/// If true, the scroll view may indicate the scrollable component of
/// the content offset, in a way suitable for the platform.
///
/// The default is `true`.
public var showsIndicators: Bool
/// The initial offset of the view as measured in the global frame
@State private var initialOffset: CGPoint?
/// The offset of the scroll view updated as the scroll view scrolls
@Binding public var scrollViewFrame: CGRect
@Binding public var offset: CGPoint
@Binding public var contentSize: CGSize
public init(_ axes: Axis.Set = .vertical,
showsIndicators: Bool = true,
offset: Binding<CGPoint> = .constant(.zero),
contentSize: Binding<CGSize> = .constant(.zero) ,
scrollViewFrame: Binding<CGRect> = .constant(.zero),
@ViewBuilder content: () -> Content) {
self.axes = axes
self.showsIndicators = showsIndicators
self._offset = offset
self._contentSize = contentSize
self.content = content()
self._scrollViewFrame = scrollViewFrame
}
public var body: some View {
ZStack {
GeometryReader { geometry in
Run {
let frame = geometry.frame(in: .global)
self.$scrollViewFrame.wrappedValue = frame
}
}
ScrollView(axes, showsIndicators: showsIndicators) {
ZStack(alignment: .leading) {
GeometryReader { geometry in
Run {
let frame = geometry.frame(in: .global)
let globalOrigin = frame.origin
self.initialOffset = self.initialOffset ?? globalOrigin
let initialOffset = (self.initialOffset ?? .zero)
let offset = CGPoint(x: globalOrigin.x - initialOffset.x, y: globalOrigin.y - initialOffset.y)
self.$offset.wrappedValue = offset
self.$contentSize.wrappedValue = frame.size
}
}
content
}
}
}
}
}
struct Run: View {
let block: () -> Void
var body: some View {
DispatchQueue.main.async(execute: block)
return AnyView(EmptyView())
}
}
extension CGPoint {
func reScale(from: CGRect, to: CGRect) -> CGPoint {
let x = (self.x - from.origin.x) / from.size.width * to.size.width + to.origin.x
let y = (self.y - from.origin.y) / from.size.height * to.size.height + to.origin.y
return .init(x: x, y: y)
}
func center(from: CGRect, to: CGRect) -> CGPoint {
let x = self.x + (to.size.width - from.size.width) / 2 - from.origin.x + to.origin.x
let y = self.y + (to.size.height - from.size.height) / 2 - from.origin.y + to.origin.y
return .init(x: x, y: y)
}
}
enum ArrowContentMode {
case center
case reScale
}
extension ArrowContentMode {
func transform(point: CGPoint, from: CGRect, to: CGRect) -> CGPoint {
switch self {
case .center:
return point.center(from: from, to: to)
case .reScale:
return point.reScale(from: from, to: to)
}
}
}
struct ArrowShape : Shape {
let contentMode : ArrowContentMode = .center
func path(in rect: CGRect) -> Path {
var path = Path()
let points = [
CGPoint(x: 0, y: 8),
CGPoint(x: 0, y: -8),
CGPoint(x: 0, y: 8),
CGPoint(x: 5.66, y: 2.34),
CGPoint(x: 0, y: 8),
CGPoint(x: -5.66, y: 2.34)
]
let minX = points.min { $0.x < $1.x }?.x ?? 0
let minY = points.min { $0.y < $1.y }?.y ?? 0
let maxX = points.max { $0.x < $1.x }?.x ?? 0
let maxY = points.max { $0.y < $1.y }?.y ?? 0
let fromRect = CGRect.init(x: minX, y: minY, width: maxX-minX, height: maxY-minY)
print("fromRect nx: ",minX,minY,maxX,maxY)
print("fromRect: \(fromRect), toRect: \(rect)")
let transformed = points.map { contentMode.transform(point: $0, from: fromRect, to: rect) }
print("fromRect: transformed=>\(transformed)")
path.move(to: transformed[0])
path.addLine(to: transformed[1])
path.move(to: transformed[2])
path.addLine(to: transformed[3])
path.move(to: transformed[4])
path.addLine(to: transformed[5])
return path
}
}
* it wont work on the scroll view
* OR block the scrolling on the scrollview content
最佳答案
您可以使用 Introspect获取 UIScrollView,然后从中获取 UIScrollView.contentOffset 和 UIScrollView.isDragging 的发布者,以获取可用于操作 SwiftUI View 的值的更新。
struct Example: View {
@State var isDraggingPublisher = Just(false).eraseToAnyPublisher()
@State var offsetPublisher = Just(.zero).eraseToAnyPublisher()
var body: some View {
...
.introspectScrollView {
self.isDraggingPublisher = $0.publisher(for: \.isDragging).eraseToAnyPublisher()
self.offsetPublisher = $0.publisher(for: \.contentOffset).eraseToAnyPublisher()
}
.onReceive(isDraggingPublisher) {
// do something with isDragging change
}
.onReceive(offsetPublisher) {
// do something with offset change
}
...
}
如果你想看一个例子;我使用此方法获取包中的偏移发布者
ScrollViewProxy .
关于SwiftUI 滚动/列表滚动事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59267131/
有没有办法获取/获取 SwiftUI 中 Text 对象中使用的当前字体?前任。 Text("abc").font() 不起作用。 最佳答案 可以从环境访问当前字体: struct ChildView
我想知道为什么 SwiftUI 中的 2 个元素之间会出现这种间距?以及如何控制/修改它?我尝试向 ExtractedView 添加一些填充,但没有任何改变。似乎它是由 .frame(height:
目标 获取要显示在scrollView中的数据 预期结果 实际结果 另类 使用List,但不灵活(无法删除分隔符,不能具有多列) 码 struct Object: Identifiable {
我想使用 onIncrement 和 onDecrement 在手动(非绑定(bind))模式下使用 Stepper View 。当我尝试实现下限和上限时,有一种奇怪的行为,例如。年龄值不低于 1 或
我正在尝试在 SwiftUI 中显示全局警报。无论当前显示/呈现在屏幕上的内容(例如工作表),此警报都应显示在所有内容的顶部。 这是我的代码: @main struct MyApp: App {
我正在尝试为我的模态表实现一个关闭按钮,如下所示: struct TestView: View { @Environment(\.isPresented) var present va
我有一个在 SwiftUI 中处理的主细节应用程序,但是一旦在第一个 DetailView 上,NavBar 中的 NavigationLink 就不再有效。我把它写成一个简单的演示: struct
这是我想做的一个最小的、可重复的例子。 我有一系列的段落。 var notes = [ "One line paragraph", "This is a small paragraph
有什么方法可以使用 SwiftUI 找到父 View 大小,我查看了文档和示例,似乎大多数(如果不是全部)都是硬编码大小,理想情况下我想找到父 View 的大小然后设置基于父级大小百分比的 subvi
我有一个 列表由单元格组成,每个单元格包含一个图像和一列文本,我希望以特定的方式布局。左侧图像,占宽度的四分之一。文本的剩余空间,左对齐。 这是我得到的代码: struct TestCell: Vie
这是 iOS 13 Health 应用程序的屏幕截图 - 用户个人资料。我最近开始使用 swiftui并想知道如何开发如下所示的屏幕。我尝试了简单和分组的列表样式。但我无法看到下面的布局。 这样的UI
更新 : 14 个月后,AppKit 发行说明中有这样一个有趣的说明: A TextField that you are editing inside a selected List row now
我来自 React,在那里我使用 useMemo 来确保某些计算不会过于频繁地执行。我如何在 SwiftUI 中做类似的事情? 考虑这个例子: struct MyView: View { va
我已经查看并尝试了所有不同的组合,但我无法弄清楚如何更改 View 导航栏标题的文本颜色。这是我的代码,我也在尝试使用我已经从我的 Assets 文件夹中添加和使用的自定义颜色。我知道这个问题已被问过
如何更改swiftUI上导航栏“返回”按钮的文本? form from a navigationLink init(){ UINavigationBar.appearance().backgr
具有渐变填充的矩形并尝试为颜色变化设置动画。 ... Rectangle() .fill(LinearGradient( gradient: .init(stops:
我已经将UITextView包装在UIViewRepresentable中,并包括了Coordinator作为UITextViewDelegate,但是未调用事件。我究竟做错了什么? struct T
我需要更改 swiftUI 中 tabItem 徽章的颜色。我创建了这个 Pod https://github.com/jogendra/BadgeHub可以与 swiftUI 一起使用吗? 我有选项
我可以使用以下代码在 UIKIt 中定义常量字体: let appFont = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.regular)
通常我可以在 SwiftUI 中显示这样的项目列表: enum Fruit { case apple case orange case banana } struct Frui
我是一名优秀的程序员,十分优秀!