optonaut / ActiveLabel.swift

UILabel drop-in replacement supporting Hashtags (#), Mentions (@) and URLs (http://) written in Swift
MIT License
4.47k stars 686 forks source link

Add padding to LabelView in swiftui does not work. #418

Open arbyruns opened 2 years ago

arbyruns commented 2 years ago

I'm attempting to add padding to the label to present the run off as shown below. Here's how I'm calling the view within SwiftUI

SUILabel(text: tweet.text, preferredMaxLayoutWidth : UIScreen.main.bounds.width - 50)
                        .fixedSize(horizontal: false, vertical: true)

image

Here's the code I'm using,

struct SUILabel: UIViewRepresentable {
    @Environment(\.openURL) var openURL

    let text: String

    var preferredMaxLayoutWidth: CGFloat = UIScreen.main.bounds.width - 50
    func makeUIView(context: UIViewRepresentableContext<SUILabel>) -> UILabel {
        let label = ActiveLabel()
        label.layoutMargins = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 25)
        label.numberOfLines = 10
        label.enabledTypes = [.mention, .hashtag, .url]
        label.hashtagColor = .systemBlue
        label.mentionColor = .systemBlue
        label.URLColor = .systemBlue
        label.text = text
        label.textColor = UITraitCollection().userInterfaceStyle == .light ? .black : .white
        label.preferredMaxLayoutWidth = UIScreen.main.bounds.width
        label.contentMode = .scaleAspectFill

        // MARK: - handle types

        label.handleHashtagTap { hashtag in
            print("Success. You just tapped the \(hashtag) hashtag")
            openURL(URL(string: "https://twitter.com/hashtag/\(hashtag)")!)
        }
        label.handleURLTap { url in
            openURL(url)
        }
        label.handleMentionTap { handle in
            openURL(URL(string: "https://twitter.com/\(handle)")!)
        }
        return label
    }

    func updateUIView(_ uiView: UILabel, context: UIViewRepresentableContext<SUILabel>) { }
}
brooksGetIt commented 1 year ago

set fixedSize(horizontal: true, vertical: true),and "label.preferredMaxLayoutWidth = UIScreen.main.bounds.width" will work for width. your code helps a lot. thx bro.