cbpowell / MarqueeLabel

A drop-in replacement for UILabel, which automatically adds a scrolling marquee effect when the label's text does not fit inside the specified frame
MIT License
4.22k stars 565 forks source link

How to wrap MarqueeLabel with using SwiftUI? #281

Open sudachi808 opened 2 years ago

sudachi808 commented 2 years ago

I want to use MarqueeLabel within SwiftUI views. But I could not work it using the code below.

How do I implement it?

import SwiftUI
import MarqueeLabel

struct MarqueeText: UIViewRepresentable {

    func makeUIView(context: Context) -> MarqueeLabel {
        MarqueeLabel(frame: .init(x: 0, y: 0, width: 100, height: 24), duration: 1.0, fadeLength: 10.0)
    }

    func updateUIView(_ uiView: MarqueeLabel, context: Context) {
        uiView.textAlignment = .center
        uiView.text = "The quick brown fox jumps over the lazy dog."
        uiView.restartLabel()
    }
}

// MARK: - Preview

struct MarqueeText_Previews: PreviewProvider {
    static var previews: some View {
        MarqueeText()
    }
}
davidkessler-ch commented 2 years ago

Use setContentCompressionResistancePriority in order for the view to actually collapse. In your example, change the updateUIView to this:

func updateUIView(_ uiView: MarqueeLabel, context: Context) {
        uiView.textAlignment = .center
        uiView.text = "The quick brown fox jumps over the lazy dog."
        uiView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
        uiView.restartLabel()
    }