SwiftUI-滑动文本动画和定位

问题描述

在学习更多关于SwiftUI的过程中,我仍然对将元素放置在ZStack中感到困惑。

目标是“简单”,我想要一个文本,如果文本太长,它将在定义的区域内滑动。 假设我有一个50px的区域,而文本需要100个像素。我希望文本从右向左滑动,然后从左向右滑动。

当前,我的代码如下:

struct ContentView: View {
    @State private var animateSliding: Bool = false
    private let timer = Timer.publish(every: 1,on: .current,in: .common).autoconnect()
    private let slideDuration: Double = 3
    private let text: String = "Hello,World! My name is Oleg and I would like this text to slide!"

    var body: some View {
        GeometryReader(content: { geometry in
            vstack(content: {
                Text("Hello,World! My name is Oleg!")
                    .font(.system(size: 20))
                    .id("SlidingText-Animation")
                    .alignmentGuide(VerticalAlignment.center,computeValue: { $0[VerticalAlignment.center] })
                    .position(y: geometry.size.height / 2 + self.textSize(fromWidth: geometry.size.width).height / 2)
                    .fixedSize()
                    .background(Color.red)
                    .animation(Animation.easeInOut(duration: 2).repeatForever())
                    .position(x: self.animateSliding ? -self.textSize(fromWidth: geometry.size.width).width : self.textSize(fromWidth: geometry.size.width).width)
                    .onAppear(perform: {
                        self.animateSliding.toggle()
                    })
            })
                .background(Color.yellow)
                .clipShape(Rectangle())
        })
            .frame(width: 200,height: 80)
    }

    func textSize(fromWidth width: CGFloat,fontName: String = "System Font",fontSize: CGFloat = UIFont.systemFontSize) -> CGSize {
        let text: UILabel = .init()
        text.text = self.text
        text.numberOfLines = 0
        text.font = UIFont.systemFont(ofSize: 20) // (name: fontName,size: fontSize)
        text.lineBreakMode = .byWordWrapping
        return text.sizeThatFits(CGSize.init(width: width,height: .infinity))
    }
}

enter image description here

您有任何建议如何将“文本”垂直放置在其父级中,以及动画是否从合适的位置开始?

感谢您将来的任何帮助,非常感谢!

编辑:

我重组了代码,并更改了我正在做的几件事。

struct SlidingText: View {
    let geometryProxy: GeometryProxy

    @State private var animateSliding: Bool = false
    private let timer = Timer.publish(every: 1,World! My name is Oleg and I would like this text to slide!"

    var body: some View {
        ZStack(alignment: .leading,content: {
            Text(text)
                .font(.system(size: 20))
//                .lineLimit(1)
                .id("SlidingText-Animation")
                .fixedSize(horizontal: true,vertical: false)
                .background(Color.red)
                .animation(Animation.easeInOut(duration: slideDuration).repeatForever())
                .offset(x: self.animateSliding ? -textSize().width : textSize().width)
                .onAppear(perform: {
                    self.animateSliding.toggle()
                })
        })
            .frame(width: self.geometryProxy.size.width,height: self.geometryProxy.size.height)
            .clipShape(Rectangle())
            .background(Color.yellow)
    }

    func textSize(fontName: String = "System Font",fontSize: CGFloat = 20) -> CGSize {
        let text: UILabel = .init()
        text.text = self.text
        text.numberOfLines = 0
        text.font = UIFont(name: fontName,size: fontSize)
        text.lineBreakMode = .byWordWrapping
        let textSize = text.sizeThatFits(CGSize(width: self.geometryProxy.size.width,height: .infinity))
        print(textSize.width)
        return textSize
    }
}

struct ContentView: View {
    var body: some View {
        GeometryReader(content: { geometry in
            SlidingText(geometryProxy: geometry)
        })
            .frame(width: 200,height: 40)

    }
}

现在,动画看起来非常不错,除了我在左右两边都有填充,我不明白为什么。

enter image description here

Edit2:我还注意到通过将text.font = UIFont.systemFont(ofSize: 20)更改为text.font = UIFont.systemFont(ofSize: 15),可以使文本正确显示。我不了解SwiftUIUIKit的系统字体之间是否有区别。它不应该..

在我的情况下,带有解决方案的最终编辑:

struct SlidingText: View {
    let geometryProxy: GeometryProxy
    @Binding var text: String
    @Binding var fontSize: CGFloat

    @State private var animateSliding: Bool = false
    private let timer = Timer.publish(every: 5,in: .common).autoconnect()
    private let slideDuration: Double = 3

    var body: some View {
            ZStack(alignment: .leading,content: {
                vstack {
                    Text(text)
                        .font(.system(size: self.fontSize))
                        .background(Color.red)
                }
                .fixedSize()
                .frame(width: geometryProxy.size.width,alignment: animateSliding ? .trailing : .leading)
                .clipped()
                .animation(Animation.linear(duration: slideDuration))
                .onReceive(timer) { _ in
                    self.animateSliding.toggle()
                }
            })
                .frame(width: self.geometryProxy.size.width,height: self.geometryProxy.size.height)
                .clipShape(Rectangle())
                .background(Color.yellow)
    }
}

struct ContentView: View {
    @State var text: String = "Hello,World! My name is Oleg and I would like this text to slide!"
    @State var fontSize: CGFloat = 20

    var body: some View {
        GeometryReader(content: { geometry in
            SlidingText(geometryProxy: geometry,text: self.$text,fontSize: self.$fontSize)
        })
            .frame(width: 400,height: 40)
        .padding(0)

    }
}

这是直观的结果。

enter image description here

解决方法

这是一种可能的简单方法-这个想法就像更改容器中的文本对齐方式一样简单,其他任何东西都可以照常进行调整。

使用Xcode 12 / iOS 14准备并测试了演示

demo

struct DemoSlideText: View {
    let text = "Lorem ipsum dolor sit amet,consetetur sadipscing elitr,sed diam nonumy eirmod tempor"

    @State private var go = false
    var body: some View {
        VStack {
            Text(text)
        }
        .fixedSize()
        .frame(width: 300,alignment: go ? .trailing : .leading)
        .clipped()
        .onAppear { self.go.toggle() }
        .animation(Animation.linear(duration: 5).repeatForever(autoreverses: true))
    }
}
,

一种实现方法是将“ PreferenceKey”协议与“ preference”和“ onPreferenceChange”修饰符结合使用。

这是SwiftUI将数据从子视图发送到父视图的方法。

代码:

struct ContentView: View {
    
    @State private var offset: CGFloat = 0.0
    
    private let text: String = "Hello,World! My name is Oleg and I would like this text to slide!"
    
    var body: some View {
        // Capturing the width of the screen
        GeometryReader { screenGeo in
            ZStack {
                Color.yellow
                    .frame(height: 50)
                
                Text(text)
                    .fixedSize()
                    .background(
                        // Capturing the width of the text
                        GeometryReader { geo in
                            Color.red
                                // Sending width difference to parent View
                                .preference(key: MyTextPreferenceKey.self,value: screenGeo.size.width - geo.frame(in: .local).width
                                )
                        }
                    )
            }
            .offset(x: self.offset)
            // Receiving width from child view
            .onPreferenceChange(MyTextPreferenceKey.self,perform: { width in
                    withAnimation(Animation.easeInOut(duration: 1).repeatForever()) {
                        self.offset = width
                    }
            })
        }
    }
}

// MARK: PreferenceKey
struct MyTextPreferenceKey: PreferenceKey {
    static var defaultValue: CGFloat = 0.0
    
    static func reduce(value: inout CGFloat,nextValue: () -> CGFloat) {
        value = nextValue()
    }
}

结果:

enter image description here

,

利用你们的灵感,我最终只使用了Animation函数/属性来做一些简单的事情。

import SwiftUI

struct SlidingText: View {
    let geometryProxy: GeometryProxy
    @Binding var text: String
    let font: Font

    @State private var animateSliding: Bool = false
    private let slideDelay: Double = 3
    private let slideDuration: Double = 6

    private var isTextLargerThanView: Bool {
        if text.size(forWidth: geometryProxy.size.width,andFont: font).width < geometryProxy.size.width {
            return false
        }
        return true
    }

    var body: some View {
        ZStack(alignment: .leading,content: {
            VStack(content: {
                Text(text)
                    .font(self.font)
                    .foregroundColor(.white)
            })
                .id("SlidingText-Animation")
                .fixedSize()
                .animation(isTextLargerThanView ? Animation.linear(duration: slideDuration).delay(slideDelay).repeatForever(autoreverses: true) : nil)
                .frame(width: geometryProxy.size.width,alignment: isTextLargerThanView ? (animateSliding ? .trailing : .leading) : .center)
                .onAppear(perform: {
                    self.animateSliding.toggle()
                })
        })
            .clipped()
    }
}

然后我叫SlidingView

GeometryReader(content: { geometry in
                    SlidingText(geometryProxy: geometry,text: self.$playerViewModel.seasonByline,font: .custom("FoundersGrotesk-RegularRegular",size: 15))
                })
                    .frame(height: 20)
                    .fixedSize(horizontal: false,vertical: true)

再次感谢您的帮助!

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...