3

I'm trying to add a marquee effect to a Text (song name) in SwiftUI, so that it scrolls horizontally across the screen if it is larger than the screen width.

I know MarqueeLabel is available for UIKit, but I haven't been able to wrap it in SwiftUI or find an alternative that works.

Help?

atdonsm
  • 265
  • 4
  • 11
  • Did you try anything yourself? Maybe wrapping in UIViewRepresentable? [How to wrap a custom UIView for SwiftUI](https://www.hackingwithswift.com/quick-start/swiftui/how-to-wrap-a-custom-uiview-for-swiftui) – pawello2222 Aug 13 '20 at 14:42
  • 1
    Yeah, I actually followed those exact instructions. For some reason the view was stretching beyond the width of my screen. – atdonsm Aug 13 '20 at 15:07

1 Answers1

1

I know this question is quite old, but for anyone who has the same question. You can wrap this in an UIViewRepresentable. like so:


struct UILabelView : UIViewRepresentable {
    
    var text: String

    typealias UIViewType = MarqueeLabel

    func makeUIView(context: UIViewRepresentableContext<UILabelView>) -> MarqueeLabel {
        
        let label = MarqueeLabel()
        label.text = text
        label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
        return label
        
    }
    
    func updateUIView(_ uiView: MarqueeLabel, context: UIViewRepresentableContext<UILabelView>) { }
    
}

and then if you have a view which has a limited with it should work:

UILabelView(text: "a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20")
                .frame(width: 40)

As for your issue in your comment "For some reason the view was stretching beyond the width of my screen." the key is to use .setContentCompressionResistancePriority(.defaultLow, for: .horizontal) on the MarqueeLabel as explained by @Asperi in this post.

D. Kee
  • 169
  • 14