如何在Swift ui底部使用ScrollView初始化视图?

时间:2019-07-08 14:06:11

标签: swift swiftui

我正在Swift UI中构建一个聊天应用程序,当我进入“ ChatView” 时,我想查看最后写入的消息,因此当消息在屏幕上时({{3 }})我需要将视图的滚动条放在底部。

这是我正在使用的代码:

ScrollView {
  ForEach(self.userController.userMessage.identified(by: \.self)) { message in
    if message.from == UserService.currentUserID! {
      HStack {
        Spacer()
        Text(message.message)
          .bold()
          .foregroundColor(Color.white)
          .padding(8)
          .background(Color.blue, cornerRadius: 8)
      }
    } else {
      HStack {
        Text(message.message)
          .bold()
          .foregroundColor(Color.white)
          .padding(8)
          .background(Color.gray, cornerRadius: 8)
        Spacer()
     }
     .offset(y: 8)
   }
  }
 }
}

如何默认将ScrollView始终放在底部?

1 个答案:

答案 0 :(得分:0)

我的解决方案是ScrollView不支持程序化滚动(至今吗?)是旋转和翻转它。

ScrollView{
    VStack{
        ForEach(items ) { item in
            Text(item.text)
              .rotationEffect(.pi) // rotate each item
              .scaleEffect(x: -1, y: 1, anchor: .center) // and flip it so we can flip the container to keep the scroll indicators on the right
        }
    }
}
.rotationEffect(.pi) // rotate the whole ScrollView 180º
.scaleEffect(x: -1, y: 1, anchor: .center) // flip it so the indicator is on the right