Flutter 版本请查看此链接
简易聊天界面,可通过内置消息单元快速上手。
cellWidth
属性,会自动缩放消息单元格)。SPM: https://github.com/EnesKaraosman/SwiftyChat.git
public enum ChatMessageKind {
/// A text message,
/// supports emoji 👍🏻 (auto scales if text is all about emojis)
case text(String)
/// An image message, from local(UIImage) or remote(URL).
case image(ImageLoadingKind)
/// A location message, pins given location & presents on MapKit.
case location(LocationItem)
/// A contact message, generally for sharing purpose.
case contact(ContactItem)
/// Multiple options, disables itself after selection.
case quickReply([QuickReplyItem])
/// `CarouselItem`s that contains title, subtitle, image & button in a scrollable view
case carousel([CarouselItem])
/// A video message, opens the given URL.
case video(VideoItem)
}
ChatView
以下是开始所需的最少代码(参见“运行并开始使用”)
详情请访问示例项目 此处
import SwiftyChat
import SwiftyChatMock
@State private var scrollToBottom = false
@State private var messages: [MockMessages.ChatMessageItem] = [] // for quick test assign MockMessages.generatedMessages()
// ChatMessageItem & ChatUserItem is a sample objects/structs
// that conforms `ChatMessage` & `ChatUser` protocols.
ChatView<MockMessages.ChatMessageItem, MockMessages.ChatUserItem>(
messages: $messages,
scrollToBottom: $scrollToBottom
) {
// InputView here, continue reading..
}
// ▼ Required
.environmentObject(
// All parameters initialized by default,
// change as you want.
ChatMessageCellStyle()
)
.onReceive(
messages.debounce(for: .milliseconds(650), scheduler: RunLoop.main),
perform: { _ in
scrollToBottom = true
}
)
// ...
InputView
您可以查看项目中的现有 BasicInputView
。
如果它适合您的需求,您可以直接使用,也可以创建一个新的。
推荐的方法是直接克隆 BasicInputView
并进行修改(例如,添加相机图标等)。
// InputBarView variables
@State private var message = ""
var inputBarView: some View {
BasicInputView(
message: $message, // Typed text.
placeholder: "Type something",
onCommit: { messageKind in
self.messages.append(
.init(user: MockMessages.sender, messageKind: messageKind, isSender: true)
)
}
)
.background(Color.primary.colorInvert())
// ▼ An extension that wraps view inside AnyView
.embedInAnyView()
}
// Pass in ChatView
ChatView(messages: $messages) {
inputBarView
}
...
...
public class ChatMessageCellStyle: ObservableObject {
let incomingTextStyle: TextCellStyle
let outgoingTextStyle: TextCellStyle
let incomingCellEdgeInsets: EdgeInsets
let outgoingCellEdgeInsets: EdgeInsets
let contactCellStyle: ContactCellStyle
let imageCellStyle: ImageCellStyle
let quickReplyCellStyle: QuickReplyCellStyle
let carouselCellStyle: CarouselCellStyle
let locationCellStyle: LocationCellStyle
let incomingAvatarStyle: AvatarStyle
let outgoingAvatarStyle: AvatarStyle
}
您必须初始化此类以构建适当的样式并将其作为 environmentObject
注入。
所有样式都有默认的初始化器;
有关详细文档,请访问 Styles.md
您也可以使用自己的自定义消息单元格,详情请参见 CustomMessage.md。