programing

텍스트가 swift UI로 감싸지지 않습니다.

javajsp 2023. 9. 6. 21:47

텍스트가 swift UI로 감싸지지 않습니다.

설정 후에도.lineLimit(nil)텍스트가 포장되지 않습니다.

var body: some View {
    VStack(alignment: .center) {
        Text("SwiftUI is a modern way to declare user interfaces for any Apple platform. ")
            .font(.title)
            .color(.red)
            .lineLimit(nil)
        Text("Create beautiful, dynamic apps faster than ever before.")
            .font(.system(size: 20))
            .lineLimit(nil)
    }.padding(EdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 10))
}

enter image description here

이와 같은 오류로 많은 시간을 보낸 후 라인 리미트 문제라고 100% 확신할 수는 없습니다.이 게시물을 작성하면서 더 복잡한 보기로 찾은 해결책은 래핑 방지를 위한 다음 코드 조각입니다.

.fixedSize(horizontal: false, vertical: true)

이렇게 하면 인터프리터가 텍스트를 세로로 접는 것을 방지할 수 있습니다.

Xcode 11.3 / Swift 5.1의 완전한 솔루션은 여기서 여러 개의 답변을 통해 확인할 수 있습니다.

왜 이런 일이 일어나는지에 대한 설명은 마테오 파치니의 대답에서 찾을 수 있습니다: 미리 정의된 것을 사용하는 것..font(.title),.font(.headline), 등이 이들의 행동을 가져온 것으로 보입니다.Text보기는 랩보다는 항상 타원 크기로 크기를 조정합니다.하지만 단순히 로 전환하는 것은.body최선의 방법은 아닌 것 같네요

가장 좋은 해결책은 샤피에네로의 답변에서 찾을 수 있습니다..fixedSize(horizontal: false, vertical: true)당신에게Text보기. 이것이 말해줍니다.Text맞춤형 크기 조정 수평 로직인 NOT 타원 크기 조정을 하지 않기 위해 모두가 익숙한 표준 규칙을 따르도록 합니다.

그들 둘 다 덕분입니다.

두 번째 텍스트의 내용을 시도합니다.lineLimit0이 아닌 숫자로:

VStack(alignment: .leading) {
  Text("SwiftUI is a modern way to declare user interfaces for any Apple platform. ")
    .font(.title)
    .color(.red)
    .lineLimit(nil)
  Text("Create beautiful, dynamic apps faster than ever before.")
    .font(.system(size: 20))
    .lineLimit(2)
 }.padding(EdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 10))

결과:

enter image description here

보아하니.font선 래핑 특성을 보유합니다.

로 변경하시면body, 그러면 제대로 감겨요!

enter image description here

제 문제를 해결하기 위해 저는 다음과 같은 설정을 했습니다.

public var body: some View {
    Form {
        Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
            .font(.title)

        Spacer()
            .fixedSize()

        Text("""
            Integer ut orci odio. Proin cursus ut elit eget rutrum. Nunc ante sem, euismod sed purus sed, tempus elementum elit. Phasellus lobortis at arcu quis porta. Cras accumsan leo eu tempus molestie. Suspendisse vulputate diam ipsum, et tristique lorem porta et. Pellentesque sodales est id arcu luctus venenatis.

            Vestibulum non magna lorem. In tincidunt aliquet nunc, sit amet pharetra neque hendrerit id.

            Cras sed!
            """)

        NativeButton("OK", keyEquivalent: .return) { self.screen = .game }
    }
        .frame(maxWidth: 480)
        .fixedSize()
        .padding()
}

Only the first line of the first `Text` and the first few lines of the second `Text` appear

어떤 이유에서인지, 제가 해야 할 일은 그저minWidth: 480, idealWidth: 480프레임과 모든 것을 올바르게 렌더링할 수 있습니다.저는 이미 신청해서 예상하지 못했습니다..fixedSize(), 그래서 이 셋 중 하나면 충분할 거라 생각했습니다.

public var body: some View {
    Form {
        Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
            .font(.title)

        Spacer()
            .fixedSize()

        Text("""
            Integer ut orci odio. Proin cursus ut elit eget rutrum. Nunc ante sem, euismod sed purus sed, tempus elementum elit. Phasellus lobortis at arcu quis porta. Cras accumsan leo eu tempus molestie. Suspendisse vulputate diam ipsum, et tristique lorem porta et. Pellentesque sodales est id arcu luctus venenatis.

            Vestibulum non magna lorem. In tincidunt aliquet nunc, sit amet pharetra neque hendrerit id.

            Cras sed!
            """)

        NativeButton("OK", keyEquivalent: .return) { self.screen = .game }
    }
        .frame(minWidth: 480, idealWidth: 480, maxWidth: 480)
        .fixedSize()
        .padding()
}

All the text appears as intended

스위프트 UI

.lineLimit(닐) VS.lineLimit(임의 숫자)

VStack(alignment: .leading, spacing: 16.0) {
// Sets the maximum number of lines that text can occupy in the view.

      Text("SwiftUI is a user interface toolkit that lets us design apps in a declarative way. ")
      .font(.title)
      .lineLimit(3)

// But if you don't know about the the text size then Sets nil in the lineLimit.

      Text("SwiftUI is a user interface toolkit that lets us design apps in a declarative way. That's a fancy way of saying that we tell SwiftUI how we want our UI to look and work, and it figures out how to make that happen as the user interacts with it.... ")
       .font(.body)
       .lineLimit(nil)
}.padding(EdgeInsets(top: 0, leading: 8, bottom: 0, trailing: 8))

저는 그와 관련된 상황이 있었습니다.UIViewRepresentable포장된UITextField다음과 같이 제시되었습니다.

VStack {
    Text("Long enough to wrap....")
    Spacer().frame(height: 40)
    CustomTextField()
}

Text추가할 때 포장이 멈췄습니다.CustomTextField. 내가 한 짓은...Text도와준만약 내가 제거했다면,Spacer()잘 마무리 되었습니다!!

결국 제거하고 말았습니다.Spacer바닥 패딩을 추가합니다.Text. 내가 알 수 있는 한, 내CustomTextField괜찮아요 왜 스위프트호에 영향을 미칠지 모르겠어요UI 레이아웃 알고리즘.

그냥 덧붙였어요.

.padding()

나에게Text예를 들어 효과가 있었습니다.

내게 도움이 된 유일한 대답은 지원하는 것이었습니다..fixedSize(horizontal: false, vertical: true)텍스트 상에서

'킨다'라고 말하는 이유는.fixedSize, Swift UI는 부모가 부여한 크기를 완전히 무시하고 오버플로합니다.부모에게 배경이 있으면 레이아웃이 망가집니다.상위 노드에 형제 노드가 있는 경우 텍스트가 그 위에 렌더링됩니다.

저는 애플이 텍스트의 이상적인 크기를 한 줄로 된 대응물 대신에 여러 줄로 된 버전으로 할 수 있는 선택권을 우리에게 주어야 한다고 믿습니다.

이런 일이 일어나지는 않지만, 저는 다음과 같은 괴물을 사용하고 있지만, 효과는 있습니다.

struct AdaptiveText: View {
  @State private var height: CGFloat?
  var text: String
  
  private func updateHeight(height: CGFloat) -> some View {
    DispatchQueue.main.async {
      self.height = height
    }
    return Color.clear
  }
  
  var body: some View {
    ZStack {
      Text(text)
        .fixedSize(horizontal: false, vertical: true)
        .background() {
          GeometryReader { geo in
            updateHeight(height: geo.size.height)
          }
        }
        .opacity(0)
      
      Text(text)
    }.frame(width: nil, height: height)
  }
}

언급URL : https://stackoverflow.com/questions/56505929/the-text-doesnt-get-wrapped-in-swift-ui