简体   繁体   English

SwiftUI:检查文本是否适合父视图,否则将其删除

[英]SwiftUI: Check if text fit in parent view, otherwise remove that

I need implement next flow in my code: Show text(1 line) and if it is cut or clipped (not fully visible) I should remove them, I don't want scale text or make it in 2 lines我需要在我的代码中实现下一个流程:显示文本(1 行),如果它被剪切或剪裁(不完全可见)我应该删除它们,我不想缩放文本或将其分成 2 行

so I found solution, this solution is compose from few different topics:所以我找到了解决方案,这个解决方案由几个不同的主题组成:

struct TruncatableText: View {
  let text: (() -> Text)
  let lineLimit: Int?
  @State private var intrinsicSize: CGSize = .zero
  @State private var truncatedSize: CGSize = .zero
  @State private var hide: Bool = false

  var body: some View {
    text()
      .lineLimit(lineLimit)
      .readSize { size in
        truncatedSize = size
        hide = truncatedSize != intrinsicSize
      }
      .background(
        text()
          .fixedSize(horizontal: false, vertical: true)
          .hidden()
          .readSize { size in
            intrinsicSize = size
            hide = truncatedSize != intrinsicSize
          }
      )
      .isShow(!hide)
  }
}

extension View {
  func readSize(onChange: @escaping (CGSize) -> Void) -> some View {
    background(
      GeometryReader { geometryProxy in
        Color.clear
          .preference(key: SizePreferenceKey.self, value: geometryProxy.size)
      }
    )
    .onPreferenceChange(SizePreferenceKey.self, perform: onChange)
  }
  
  @ViewBuilder func isShow(_ show: Bool) -> some View {
    if show {
      self
    } else {
      self.hidden()
    }
  }
}

struct SizePreferenceKey: PreferenceKey {
  static var defaultValue: CGSize = .zero
  static func reduce(value: inout CGSize, nextValue: () -> CGSize) {}
}

and using it:并使用它:

 TruncatableText(
          text: {
            Text("title")
              .font(.system(size: 21, weight: .semibold))
              .foregroundColor(Color.blue)
          },
          lineLimit: 1
        )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM