Merge pull request #803 from MessageKit/update-example

All-New ChatExample app
This commit is contained in:
Nathan Tannar
2018-08-21 19:21:44 -07:00
committed by GitHub
59 changed files with 1996 additions and 595 deletions
+4 -4
View File
@@ -12,7 +12,7 @@ jobs:
# Specify the Xcode version to use.
macos:
xcode: "9.2.0"
xcode: "9.4.1"
# Define the steps required to build the project.
steps:
@@ -29,10 +29,10 @@ jobs:
name: Bootstrap Carthage
command: carthage bootstrap --platform ios
- run:
name: Biuld framework
name: Build framework
command: xcodebuild build -project MessageKit.xcodeproj -scheme MessageKit -destination "$DESTINATION" CODE_SIGNING_REQUIRED=NO | xcpretty -c
- run:
name: Biuld and run tests
name: Build and run tests
command: xcodebuild test -project MessageKit.xcodeproj -scheme MessageKitTests -destination "$DESTINATION" CODE_SIGNING_REQUIRED=NO | xcpretty -c
- run:
name: Fetch CocoaPods Specs
@@ -41,7 +41,7 @@ jobs:
name: Update Pods
command: cd Example && pod install
- run:
name: Biuld and analyze Example
name: Build and analyze Example
command: xcodebuild build analyze -workspace Example/ChatExample.xcworkspace -scheme ChatExample -destination "$DESTINATION" ONLY_ACTIVE_ARCH=NO CODE_SIGNING_REQUIRED=NO | xcpretty -c
# Run tests.
+118 -31
View File
@@ -7,21 +7,31 @@
objects = {
/* Begin PBXBuildFile section */
37D3EAC41F390E5F00DD6A55 /* SampleData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37D3EAC31F390E5F00DD6A55 /* SampleData.swift */; };
385C2922211FF32E0010B4BA /* CustomCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 385C2920211FF32E0010B4BA /* CustomCell.swift */; };
385C2923211FF32E0010B4BA /* TableViewCells.swift in Sources */ = {isa = PBXBuildFile; fileRef = 385C2921211FF32E0010B4BA /* TableViewCells.swift */; };
385C2927211FF33B0010B4BA /* MockSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 385C2925211FF33A0010B4BA /* MockSocket.swift */; };
385C2928211FF33B0010B4BA /* MockMessage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 385C2926211FF33B0010B4BA /* MockMessage.swift */; };
385C292B211FF3450010B4BA /* Settings+UserDefaults.swift in Sources */ = {isa = PBXBuildFile; fileRef = 385C292A211FF3450010B4BA /* Settings+UserDefaults.swift */; };
385C292D211FF3520010B4BA /* CustomMessageFlowLayout.swift in Sources */ = {isa = PBXBuildFile; fileRef = 385C292C211FF3520010B4BA /* CustomMessageFlowLayout.swift */; };
385C2931211FF3630010B4BA /* UIColor+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 385C292F211FF3630010B4BA /* UIColor+Extensions.swift */; };
385C2932211FF3630010B4BA /* UIViewController+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 385C2930211FF3630010B4BA /* UIViewController+Extensions.swift */; };
385C2937211FF37B0010B4BA /* SampleData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 385C2934211FF37A0010B4BA /* SampleData.swift */; };
385C2939211FF37B0010B4BA /* Lorem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 385C2936211FF37B0010B4BA /* Lorem.swift */; };
385C2942211FF38F0010B4BA /* AdvancedExampleViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 385C293B211FF38E0010B4BA /* AdvancedExampleViewController.swift */; };
385C2943211FF38F0010B4BA /* SettingsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 385C293C211FF38E0010B4BA /* SettingsViewController.swift */; };
385C2944211FF38F0010B4BA /* MessageContainerController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 385C293D211FF38F0010B4BA /* MessageContainerController.swift */; };
385C2945211FF38F0010B4BA /* NavigationController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 385C293E211FF38F0010B4BA /* NavigationController.swift */; };
385C2946211FF38F0010B4BA /* LaunchViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 385C293F211FF38F0010B4BA /* LaunchViewController.swift */; };
385C2947211FF38F0010B4BA /* BasicExampleViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 385C2940211FF38F0010B4BA /* BasicExampleViewController.swift */; };
385C2948211FF38F0010B4BA /* ChatViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 385C2941211FF38F0010B4BA /* ChatViewController.swift */; };
882B5E811CF7D53600B6E160 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 882B5E781CF7D53600B6E160 /* AppDelegate.swift */; };
882B5E821CF7D53600B6E160 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 882B5E791CF7D53600B6E160 /* Assets.xcassets */; };
882B5E831CF7D53600B6E160 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 882B5E7A1CF7D53600B6E160 /* LaunchScreen.storyboard */; };
882B5E851CF7D53600B6E160 /* InboxViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 882B5E7E1CF7D53600B6E160 /* InboxViewController.swift */; };
882B5E871CF7D53600B6E160 /* SettingsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 882B5E801CF7D53600B6E160 /* SettingsViewController.swift */; };
882B5E901CF7D56000B6E160 /* ChatExampleUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 882B5E8E1CF7D56000B6E160 /* ChatExampleUITests.swift */; };
882B5E951CF7D56E00B6E160 /* ChatExampleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 882B5E931CF7D56E00B6E160 /* ChatExampleTests.swift */; };
A444625E4F1C8CB1B33A17F8 /* Pods_ChatExampleUITests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2AC6E3F5C11E39F57598DBE6 /* Pods_ChatExampleUITests.framework */; };
B0655A331F23E90800542A83 /* ConversationViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = B0655A321F23E90800542A83 /* ConversationViewController.swift */; };
B096438B1F288D47004D0129 /* MockMessage.swift in Sources */ = {isa = PBXBuildFile; fileRef = B096438A1F288D47004D0129 /* MockMessage.swift */; };
C1DF6DF39F66906000EC76CF /* Pods_ChatExampleTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56F0AC85B38034EC92CCBC7D /* Pods_ChatExampleTests.framework */; };
C7CA53A1B85256A5097E7DC7 /* Pods_ChatExample.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3B316705C4717C3B4C916D62 /* Pods_ChatExample.framework */; };
CAB36EA12007A573009995ED /* TableViewCells.swift in Sources */ = {isa = PBXBuildFile; fileRef = CAB36EA02007A573009995ED /* TableViewCells.swift */; };
CAB36EA32007B1B7009995ED /* Settings+UserDefaults.swift in Sources */ = {isa = PBXBuildFile; fileRef = CAB36EA22007B1B7009995ED /* Settings+UserDefaults.swift */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
@@ -57,7 +67,23 @@
/* Begin PBXFileReference section */
0364943D08CDBE656E6F6DF8 /* Pods-ChatExampleTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ChatExampleTests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-ChatExampleTests/Pods-ChatExampleTests.debug.xcconfig"; sourceTree = "<group>"; };
2AC6E3F5C11E39F57598DBE6 /* Pods_ChatExampleUITests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_ChatExampleUITests.framework; sourceTree = BUILT_PRODUCTS_DIR; };
37D3EAC31F390E5F00DD6A55 /* SampleData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SampleData.swift; sourceTree = "<group>"; };
385C2920211FF32E0010B4BA /* CustomCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CustomCell.swift; sourceTree = "<group>"; };
385C2921211FF32E0010B4BA /* TableViewCells.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableViewCells.swift; sourceTree = "<group>"; };
385C2925211FF33A0010B4BA /* MockSocket.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MockSocket.swift; sourceTree = "<group>"; };
385C2926211FF33B0010B4BA /* MockMessage.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MockMessage.swift; sourceTree = "<group>"; };
385C292A211FF3450010B4BA /* Settings+UserDefaults.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Settings+UserDefaults.swift"; sourceTree = "<group>"; };
385C292C211FF3520010B4BA /* CustomMessageFlowLayout.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CustomMessageFlowLayout.swift; sourceTree = "<group>"; };
385C292F211FF3630010B4BA /* UIColor+Extensions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UIColor+Extensions.swift"; sourceTree = "<group>"; };
385C2930211FF3630010B4BA /* UIViewController+Extensions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UIViewController+Extensions.swift"; sourceTree = "<group>"; };
385C2934211FF37A0010B4BA /* SampleData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SampleData.swift; sourceTree = "<group>"; };
385C2936211FF37B0010B4BA /* Lorem.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Lorem.swift; sourceTree = "<group>"; };
385C293B211FF38E0010B4BA /* AdvancedExampleViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AdvancedExampleViewController.swift; sourceTree = "<group>"; };
385C293C211FF38E0010B4BA /* SettingsViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SettingsViewController.swift; sourceTree = "<group>"; };
385C293D211FF38F0010B4BA /* MessageContainerController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MessageContainerController.swift; sourceTree = "<group>"; };
385C293E211FF38F0010B4BA /* NavigationController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NavigationController.swift; sourceTree = "<group>"; };
385C293F211FF38F0010B4BA /* LaunchViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LaunchViewController.swift; sourceTree = "<group>"; };
385C2940211FF38F0010B4BA /* BasicExampleViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BasicExampleViewController.swift; sourceTree = "<group>"; };
385C2941211FF38F0010B4BA /* ChatViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ChatViewController.swift; sourceTree = "<group>"; };
3B316705C4717C3B4C916D62 /* Pods_ChatExample.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_ChatExample.framework; sourceTree = BUILT_PRODUCTS_DIR; };
56F0AC85B38034EC92CCBC7D /* Pods_ChatExampleTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_ChatExampleTests.framework; sourceTree = BUILT_PRODUCTS_DIR; };
882B5E331CF7D4B900B6E160 /* ChatExample.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = ChatExample.app; sourceTree = BUILT_PRODUCTS_DIR; };
@@ -66,22 +92,16 @@
882B5E781CF7D53600B6E160 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
882B5E791CF7D53600B6E160 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
882B5E7B1CF7D53600B6E160 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
882B5E7E1CF7D53600B6E160 /* InboxViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InboxViewController.swift; sourceTree = "<group>"; };
882B5E7F1CF7D53600B6E160 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
882B5E801CF7D53600B6E160 /* SettingsViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SettingsViewController.swift; sourceTree = "<group>"; };
882B5E8E1CF7D56000B6E160 /* ChatExampleUITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ChatExampleUITests.swift; sourceTree = "<group>"; };
882B5E8F1CF7D56000B6E160 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
882B5E931CF7D56E00B6E160 /* ChatExampleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ChatExampleTests.swift; sourceTree = "<group>"; };
882B5E941CF7D56E00B6E160 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
9E0D67CD75BA7EB323FD391B /* Pods-ChatExample.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ChatExample.release.xcconfig"; path = "Pods/Target Support Files/Pods-ChatExample/Pods-ChatExample.release.xcconfig"; sourceTree = "<group>"; };
A830E27DBE0B66B89C5D2EB8 /* Pods-ChatExample.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ChatExample.debug.xcconfig"; path = "Pods/Target Support Files/Pods-ChatExample/Pods-ChatExample.debug.xcconfig"; sourceTree = "<group>"; };
B0655A321F23E90800542A83 /* ConversationViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ConversationViewController.swift; sourceTree = "<group>"; };
B096438A1F288D47004D0129 /* MockMessage.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MockMessage.swift; sourceTree = "<group>"; };
B0DD3C951C9D064B5E6D6644 /* Pods-ChatExampleUITests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ChatExampleUITests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-ChatExampleUITests/Pods-ChatExampleUITests.debug.xcconfig"; sourceTree = "<group>"; };
B2F1C412A96DE613A0AC31F8 /* Pods-ChatExampleUITests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ChatExampleUITests.release.xcconfig"; path = "Pods/Target Support Files/Pods-ChatExampleUITests/Pods-ChatExampleUITests.release.xcconfig"; sourceTree = "<group>"; };
BFE5859D088A740A7D43E1B1 /* Pods-ChatExampleTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ChatExampleTests.release.xcconfig"; path = "Pods/Target Support Files/Pods-ChatExampleTests/Pods-ChatExampleTests.release.xcconfig"; sourceTree = "<group>"; };
CAB36EA02007A573009995ED /* TableViewCells.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableViewCells.swift; sourceTree = "<group>"; };
CAB36EA22007B1B7009995ED /* Settings+UserDefaults.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Settings+UserDefaults.swift"; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@@ -112,6 +132,64 @@
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
385C2924211FF3310010B4BA /* Views */ = {
isa = PBXGroup;
children = (
385C2920211FF32E0010B4BA /* CustomCell.swift */,
385C2921211FF32E0010B4BA /* TableViewCells.swift */,
);
path = Views;
sourceTree = "<group>";
};
385C2929211FF33D0010B4BA /* Models */ = {
isa = PBXGroup;
children = (
385C2926211FF33B0010B4BA /* MockMessage.swift */,
385C2925211FF33A0010B4BA /* MockSocket.swift */,
);
path = Models;
sourceTree = "<group>";
};
385C292E211FF3540010B4BA /* Layout */ = {
isa = PBXGroup;
children = (
385C292C211FF3520010B4BA /* CustomMessageFlowLayout.swift */,
);
path = Layout;
sourceTree = "<group>";
};
385C2933211FF3670010B4BA /* Extensions */ = {
isa = PBXGroup;
children = (
385C292F211FF3630010B4BA /* UIColor+Extensions.swift */,
385C2930211FF3630010B4BA /* UIViewController+Extensions.swift */,
);
path = Extensions;
sourceTree = "<group>";
};
385C293A211FF3800010B4BA /* Data Generation */ = {
isa = PBXGroup;
children = (
385C2936211FF37B0010B4BA /* Lorem.swift */,
385C2934211FF37A0010B4BA /* SampleData.swift */,
);
path = "Data Generation";
sourceTree = "<group>";
};
385C2949211FF3930010B4BA /* View Controllers */ = {
isa = PBXGroup;
children = (
385C293B211FF38E0010B4BA /* AdvancedExampleViewController.swift */,
385C2940211FF38F0010B4BA /* BasicExampleViewController.swift */,
385C2941211FF38F0010B4BA /* ChatViewController.swift */,
385C293F211FF38F0010B4BA /* LaunchViewController.swift */,
385C293D211FF38F0010B4BA /* MessageContainerController.swift */,
385C293E211FF38F0010B4BA /* NavigationController.swift */,
385C293C211FF38E0010B4BA /* SettingsViewController.swift */,
);
path = "View Controllers";
sourceTree = "<group>";
};
7523553CCB4B87460CE4DED6 /* Pods */ = {
isa = PBXGroup;
children = (
@@ -151,16 +229,16 @@
isa = PBXGroup;
children = (
882B5E781CF7D53600B6E160 /* AppDelegate.swift */,
B0655A321F23E90800542A83 /* ConversationViewController.swift */,
37D3EAC31F390E5F00DD6A55 /* SampleData.swift */,
882B5E7E1CF7D53600B6E160 /* InboxViewController.swift */,
B096438A1F288D47004D0129 /* MockMessage.swift */,
882B5E801CF7D53600B6E160 /* SettingsViewController.swift */,
385C2949211FF3930010B4BA /* View Controllers */,
385C293A211FF3800010B4BA /* Data Generation */,
385C292E211FF3540010B4BA /* Layout */,
385C2929211FF33D0010B4BA /* Models */,
385C2924211FF3310010B4BA /* Views */,
882B5E791CF7D53600B6E160 /* Assets.xcassets */,
882B5E7F1CF7D53600B6E160 /* Info.plist */,
882B5E7A1CF7D53600B6E160 /* LaunchScreen.storyboard */,
CAB36EA02007A573009995ED /* TableViewCells.swift */,
CAB36EA22007B1B7009995ED /* Settings+UserDefaults.swift */,
385C292A211FF3450010B4BA /* Settings+UserDefaults.swift */,
385C2933211FF3670010B4BA /* Extensions */,
);
path = Sources;
sourceTree = "<group>";
@@ -267,7 +345,6 @@
TargetAttributes = {
882B5E321CF7D4B900B6E160 = {
CreatedOnToolsVersion = 7.3.1;
DevelopmentTeam = T26M4385KK;
LastSwiftMigration = 0800;
};
882B5E481CF7D4B900B6E160 = {
@@ -420,14 +497,24 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
CAB36EA12007A573009995ED /* TableViewCells.swift in Sources */,
CAB36EA32007B1B7009995ED /* Settings+UserDefaults.swift in Sources */,
882B5E871CF7D53600B6E160 /* SettingsViewController.swift in Sources */,
37D3EAC41F390E5F00DD6A55 /* SampleData.swift in Sources */,
B096438B1F288D47004D0129 /* MockMessage.swift in Sources */,
385C2922211FF32E0010B4BA /* CustomCell.swift in Sources */,
385C2946211FF38F0010B4BA /* LaunchViewController.swift in Sources */,
385C2939211FF37B0010B4BA /* Lorem.swift in Sources */,
385C2928211FF33B0010B4BA /* MockMessage.swift in Sources */,
385C2923211FF32E0010B4BA /* TableViewCells.swift in Sources */,
385C2942211FF38F0010B4BA /* AdvancedExampleViewController.swift in Sources */,
385C2937211FF37B0010B4BA /* SampleData.swift in Sources */,
385C2931211FF3630010B4BA /* UIColor+Extensions.swift in Sources */,
385C2932211FF3630010B4BA /* UIViewController+Extensions.swift in Sources */,
385C292B211FF3450010B4BA /* Settings+UserDefaults.swift in Sources */,
385C2945211FF38F0010B4BA /* NavigationController.swift in Sources */,
385C2948211FF38F0010B4BA /* ChatViewController.swift in Sources */,
385C2944211FF38F0010B4BA /* MessageContainerController.swift in Sources */,
385C2943211FF38F0010B4BA /* SettingsViewController.swift in Sources */,
385C2927211FF33B0010B4BA /* MockSocket.swift in Sources */,
385C2947211FF38F0010B4BA /* BasicExampleViewController.swift in Sources */,
882B5E811CF7D53600B6E160 /* AppDelegate.swift in Sources */,
B0655A331F23E90800542A83 /* ConversationViewController.swift in Sources */,
882B5E851CF7D53600B6E160 /* InboxViewController.swift in Sources */,
385C292D211FF3520010B4BA /* CustomMessageFlowLayout.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -587,7 +674,7 @@
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
DEVELOPMENT_TEAM = T26M4385KK;
DEVELOPMENT_TEAM = "";
INFOPLIST_FILE = "$(SRCROOT)/Sources/Info.plist";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.messagekit.ChatExample;
@@ -602,7 +689,7 @@
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
DEVELOPMENT_TEAM = T26M4385KK;
DEVELOPMENT_TEAM = "";
INFOPLIST_FILE = "$(SRCROOT)/Sources/Info.plist";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.messagekit.ChatExample;
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0930"
LastUpgradeVersion = "0940"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0930"
LastUpgradeVersion = "0940"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
+3 -3
View File
@@ -1,5 +1,5 @@
PODS:
- MessageKit (0.13.4)
- MessageKit (1.0.0)
DEPENDENCIES:
- MessageKit (from `../`)
@@ -9,8 +9,8 @@ EXTERNAL SOURCES:
:path: "../"
SPEC CHECKSUMS:
MessageKit: f51122543e9ba8b521e5eab58b0385bd7ce47a10
MessageKit: 999e5a5d065b24061c921f6404bde3b795c17722
PODFILE CHECKSUM: cecdb7bc8129cf99f66de9f68eea3256fec30c3d
COCOAPODS: 1.5.0
COCOAPODS: 1.5.3
+3 -4
View File
@@ -29,13 +29,12 @@ final internal class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]? = nil) -> Bool {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UIApplication.shared.statusBarStyle = .lightContent
window = UIWindow(frame: UIScreen.main.bounds)
window?.backgroundColor = .white
window?.rootViewController = UINavigationController(rootViewController: InboxViewController())
window?.rootViewController = NavigationController(rootViewController: LaunchViewController())
window?.makeKeyAndVisible()
return true
}
@@ -0,0 +1,21 @@
{
"images" : [
{
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "Nathan.jpg",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 177 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

@@ -0,0 +1,21 @@
{
"images" : [
{
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "7445580.jpeg",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

@@ -0,0 +1,21 @@
{
"images" : [
{
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "5061845.png",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
@@ -0,0 +1,21 @@
{
"images" : [
{
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "icons8-apple_app_store_filled.png",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

@@ -2,11 +2,11 @@
"images" : [
{
"idiom" : "universal",
"filename" : "icons8-email_filled.png",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "icons8-email.png",
"scale" : "2x"
},
{
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.6 KiB

@@ -2,11 +2,11 @@
"images" : [
{
"idiom" : "universal",
"filename" : "icons8-compact_camera_filled.png",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "icons8-camera.png",
"scale" : "2x"
},
{
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

@@ -2,11 +2,11 @@
"images" : [
{
"idiom" : "universal",
"filename" : "icons8-hashtag_filled.png",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "icons8-hashtag.png",
"scale" : "2x"
},
{
Binary file not shown.

After

Width:  |  Height:  |  Size: 523 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 675 B

@@ -0,0 +1,21 @@
{
"images" : [
{
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "icons8-info.png",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

@@ -2,11 +2,11 @@
"images" : [
{
"idiom" : "universal",
"filename" : "icons8-stack_of_photos_filled.png",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "icons8-medium_icons.png",
"scale" : "2x"
},
{
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 KiB

@@ -0,0 +1,21 @@
{
"images" : [
{
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "icons8-like_it.png",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

@@ -0,0 +1,21 @@
{
"images" : [
{
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "icons8-map_pin-1.png",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

@@ -0,0 +1,21 @@
{
"images" : [
{
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "icons8-microphone.png",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 729 B

@@ -0,0 +1,21 @@
{
"images" : [
{
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "icons8-sent.png",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 969 B

@@ -0,0 +1,21 @@
{
"images" : [
{
"idiom" : "universal",
"filename" : "grey-crowned-crane-bird-crane-animal-45853.jpeg",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

@@ -0,0 +1,21 @@
{
"images" : [
{
"idiom" : "universal",
"filename" : "pexels-photo-145939.jpeg",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

@@ -1,461 +0,0 @@
/*
MIT License
Copyright (c) 2017-2018 MessageKit
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import UIKit
import MessageKit
import MapKit
internal class ConversationViewController: MessagesViewController {
let refreshControl = UIRefreshControl()
var messageList: [MockMessage] = []
var isTyping = false
lazy var formatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .medium
return formatter
}()
override func viewDidLoad() {
super.viewDidLoad()
let messagesToFetch = UserDefaults.standard.mockMessagesCount()
DispatchQueue.global(qos: .userInitiated).async {
SampleData.shared.getMessages(count: messagesToFetch) { messages in
DispatchQueue.main.async {
self.messageList = messages
self.messagesCollectionView.reloadData()
self.messagesCollectionView.scrollToBottom()
}
}
}
messagesCollectionView.messagesDataSource = self
messagesCollectionView.messagesLayoutDelegate = self
messagesCollectionView.messagesDisplayDelegate = self
messagesCollectionView.messageCellDelegate = self
messageInputBar.delegate = self
messageInputBar.sendButton.tintColor = UIColor(red: 69/255, green: 193/255, blue: 89/255, alpha: 1)
scrollsToBottomOnKeybordBeginsEditing = true // default false
maintainPositionOnKeyboardFrameChanged = true // default false
messagesCollectionView.addSubview(refreshControl)
refreshControl.addTarget(self, action: #selector(ConversationViewController.loadMoreMessages), for: .valueChanged)
navigationItem.rightBarButtonItems = [
UIBarButtonItem(image: UIImage(named: "ic_keyboard"),
style: .plain,
target: self,
action: #selector(ConversationViewController.handleKeyboardButton)),
UIBarButtonItem(image: UIImage(named: "ic_typing"),
style: .plain,
target: self,
action: #selector(ConversationViewController.handleTyping))
]
}
@objc func handleTyping() {
defer {
isTyping = !isTyping
}
if isTyping {
messageInputBar.topStackView.arrangedSubviews.first?.removeFromSuperview()
messageInputBar.topStackViewPadding = .zero
} else {
let label = UILabel()
label.text = "nathan.tannar is typing..."
label.font = UIFont.boldSystemFont(ofSize: 16)
messageInputBar.topStackView.addArrangedSubview(label)
messageInputBar.topStackViewPadding.top = 6
messageInputBar.topStackViewPadding.left = 12
// The backgroundView doesn't include the topStackView. This is so things in the topStackView can have transparent backgrounds if you need it that way or another color all together
messageInputBar.backgroundColor = messageInputBar.backgroundView.backgroundColor
}
}
@objc func loadMoreMessages() {
DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: DispatchTime.now() + 4) {
SampleData.shared.getMessages(count: 10) { messages in
DispatchQueue.main.async {
self.messageList.insert(contentsOf: messages, at: 0)
self.messagesCollectionView.reloadDataAndKeepOffset()
self.refreshControl.endRefreshing()
}
}
}
}
@objc func handleKeyboardButton() {
messageInputBar.inputTextView.resignFirstResponder()
let actionSheetController = UIAlertController(title: "Change Keyboard Style", message: nil, preferredStyle: .actionSheet)
let actions = [
UIAlertAction(title: "Slack", style: .default, handler: { _ in
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
self.slack()
})
}),
UIAlertAction(title: "iMessage", style: .default, handler: { _ in
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
self.iMessage()
})
}),
UIAlertAction(title: "Default", style: .default, handler: { _ in
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
self.defaultStyle()
})
}),
UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
]
actions.forEach { actionSheetController.addAction($0) }
actionSheetController.view.tintColor = UIColor(red: 69/255, green: 193/255, blue: 89/255, alpha: 1)
present(actionSheetController, animated: true, completion: nil)
}
// MARK: - Keyboard Style
func slack() {
defaultStyle()
messageInputBar.backgroundView.backgroundColor = .white
messageInputBar.isTranslucent = false
messageInputBar.inputTextView.backgroundColor = .clear
messageInputBar.inputTextView.layer.borderWidth = 0
let items = [
makeButton(named: "ic_camera").onTextViewDidChange { button, textView in
button.isEnabled = textView.text.isEmpty
},
makeButton(named: "ic_at").onSelected {
$0.tintColor = UIColor(red: 69/255, green: 193/255, blue: 89/255, alpha: 1)
},
makeButton(named: "ic_hashtag").onSelected {
$0.tintColor = UIColor(red: 69/255, green: 193/255, blue: 89/255, alpha: 1)
},
.flexibleSpace,
makeButton(named: "ic_library").onTextViewDidChange { button, textView in
button.tintColor = UIColor(red: 69/255, green: 193/255, blue: 89/255, alpha: 1)
button.isEnabled = textView.text.isEmpty
},
messageInputBar.sendButton
.configure {
$0.layer.cornerRadius = 8
$0.layer.borderWidth = 1.5
$0.layer.borderColor = $0.titleColor(for: .disabled)?.cgColor
$0.setTitleColor(.white, for: .normal)
$0.setTitleColor(.white, for: .highlighted)
$0.setSize(CGSize(width: 52, height: 30), animated: true)
}.onDisabled {
$0.layer.borderColor = $0.titleColor(for: .disabled)?.cgColor
$0.backgroundColor = .white
}.onEnabled {
$0.backgroundColor = UIColor(red: 69/255, green: 193/255, blue: 89/255, alpha: 1)
$0.layer.borderColor = UIColor.clear.cgColor
}.onSelected {
// We use a transform becuase changing the size would cause the other views to relayout
$0.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
}.onDeselected {
$0.transform = CGAffineTransform.identity
}
]
items.forEach { $0.tintColor = .lightGray }
// We can change the container insets if we want
messageInputBar.inputTextView.textContainerInset = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
messageInputBar.inputTextView.placeholderLabelInsets = UIEdgeInsets(top: 8, left: 5, bottom: 8, right: 5)
// Since we moved the send button to the bottom stack lets set the right stack width to 0
messageInputBar.setRightStackViewWidthConstant(to: 0, animated: true)
// Finally set the items
messageInputBar.setStackViewItems(items, forStack: .bottom, animated: true)
}
func iMessage() {
defaultStyle()
messageInputBar.isTranslucent = false
messageInputBar.backgroundView.backgroundColor = .white
messageInputBar.separatorLine.isHidden = true
messageInputBar.inputTextView.backgroundColor = UIColor(red: 245/255, green: 245/255, blue: 245/255, alpha: 1)
messageInputBar.inputTextView.placeholderTextColor = UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1)
messageInputBar.inputTextView.textContainerInset = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 36)
messageInputBar.inputTextView.placeholderLabelInsets = UIEdgeInsets(top: 8, left: 20, bottom: 8, right: 36)
messageInputBar.inputTextView.layer.borderColor = UIColor(red: 200/255, green: 200/255, blue: 200/255, alpha: 1).cgColor
messageInputBar.inputTextView.layer.borderWidth = 1.0
messageInputBar.inputTextView.layer.cornerRadius = 16.0
messageInputBar.inputTextView.layer.masksToBounds = true
messageInputBar.inputTextView.scrollIndicatorInsets = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
messageInputBar.setRightStackViewWidthConstant(to: 36, animated: true)
messageInputBar.setStackViewItems([messageInputBar.sendButton], forStack: .right, animated: true)
messageInputBar.sendButton.imageView?.backgroundColor = UIColor(red: 69/255, green: 193/255, blue: 89/255, alpha: 1)
messageInputBar.sendButton.contentEdgeInsets = UIEdgeInsets(top: 2, left: 2, bottom: 2, right: 2)
messageInputBar.sendButton.setSize(CGSize(width: 36, height: 36), animated: true)
messageInputBar.sendButton.image = #imageLiteral(resourceName: "ic_up")
messageInputBar.sendButton.title = nil
messageInputBar.sendButton.imageView?.layer.cornerRadius = 16
messageInputBar.sendButton.backgroundColor = .clear
messageInputBar.textViewPadding.right = -38
}
func defaultStyle() {
let newMessageInputBar = MessageInputBar()
newMessageInputBar.sendButton.tintColor = UIColor(red: 69/255, green: 193/255, blue: 89/255, alpha: 1)
newMessageInputBar.delegate = self
messageInputBar = newMessageInputBar
reloadInputViews()
}
// MARK: - Helpers
func makeButton(named: String) -> InputBarButtonItem {
return InputBarButtonItem()
.configure {
$0.spacing = .fixed(10)
$0.image = UIImage(named: named)?.withRenderingMode(.alwaysTemplate)
$0.setSize(CGSize(width: 30, height: 30), animated: true)
}.onSelected {
$0.tintColor = UIColor(red: 69/255, green: 193/255, blue: 89/255, alpha: 1)
}.onDeselected {
$0.tintColor = UIColor.lightGray
}.onTouchUpInside { _ in
print("Item Tapped")
}
}
}
// MARK: - MessagesDataSource
extension ConversationViewController: MessagesDataSource {
func currentSender() -> Sender {
return SampleData.shared.currentSender
}
func numberOfSections(in messagesCollectionView: MessagesCollectionView) -> Int {
return messageList.count
}
func messageForItem(at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageType {
return messageList[indexPath.section]
}
func cellTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
if indexPath.section % 3 == 0 {
return NSAttributedString(string: MessageKitDateFormatter.shared.string(from: message.sentDate), attributes: [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 10), NSAttributedStringKey.foregroundColor: UIColor.darkGray])
}
return nil
}
func messageTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
let name = message.sender.displayName
return NSAttributedString(string: name, attributes: [NSAttributedStringKey.font: UIFont.preferredFont(forTextStyle: .caption1)])
}
func messageBottomLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
let dateString = formatter.string(from: message.sentDate)
return NSAttributedString(string: dateString, attributes: [NSAttributedStringKey.font: UIFont.preferredFont(forTextStyle: .caption2)])
}
}
// MARK: - MessagesDisplayDelegate
extension ConversationViewController: MessagesDisplayDelegate {
// MARK: - Text Messages
func textColor(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> UIColor {
return isFromCurrentSender(message: message) ? .white : .darkText
}
func detectorAttributes(for detector: DetectorType, and message: MessageType, at indexPath: IndexPath) -> [NSAttributedStringKey: Any] {
return MessageLabel.defaultAttributes
}
func enabledDetectors(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> [DetectorType] {
return [.url, .address, .phoneNumber, .date, .transitInformation]
}
// MARK: - All Messages
func backgroundColor(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> UIColor {
return isFromCurrentSender(message: message) ? UIColor(red: 69/255, green: 193/255, blue: 89/255, alpha: 1) : UIColor(red: 230/255, green: 230/255, blue: 230/255, alpha: 1)
}
func messageStyle(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageStyle {
let corner: MessageStyle.TailCorner = isFromCurrentSender(message: message) ? .bottomRight : .bottomLeft
return .bubbleTail(corner, .curved)
// let configurationClosure = { (view: MessageContainerView) in}
// return .custom(configurationClosure)
}
func configureAvatarView(_ avatarView: AvatarView, for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) {
let avatar = SampleData.shared.getAvatarFor(sender: message.sender)
avatarView.set(avatar: avatar)
}
// MARK: - Location Messages
func annotationViewForLocation(message: MessageType, at indexPath: IndexPath, in messageCollectionView: MessagesCollectionView) -> MKAnnotationView? {
let annotationView = MKAnnotationView(annotation: nil, reuseIdentifier: nil)
let pinImage = #imageLiteral(resourceName: "pin")
annotationView.image = pinImage
annotationView.centerOffset = CGPoint(x: 0, y: -pinImage.size.height / 2)
return annotationView
}
func animationBlockForLocation(message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> ((UIImageView) -> Void)? {
return { view in
view.layer.transform = CATransform3DMakeScale(0, 0, 0)
view.alpha = 0.0
UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0, options: [], animations: {
view.layer.transform = CATransform3DIdentity
view.alpha = 1.0
}, completion: nil)
}
}
func snapshotOptionsForLocation(message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> LocationMessageSnapshotOptions {
return LocationMessageSnapshotOptions()
}
}
// MARK: - MessagesLayoutDelegate
extension ConversationViewController: MessagesLayoutDelegate {
func cellTopLabelHeight(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGFloat {
if indexPath.section % 3 == 0 {
return 10
}
return 0
}
func messageTopLabelHeight(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGFloat {
return 16
}
func messageBottomLabelHeight(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGFloat {
return 16
}
}
// MARK: - MessageCellDelegate
extension ConversationViewController: MessageCellDelegate {
func didTapAvatar(in cell: MessageCollectionViewCell) {
print("Avatar tapped")
}
func didTapMessage(in cell: MessageCollectionViewCell) {
print("Message tapped")
}
func didTapCellTopLabel(in cell: MessageCollectionViewCell) {
print("Top cell label tapped")
}
func didTapMessageTopLabel(in cell: MessageCollectionViewCell) {
print("Top message label tapped")
}
func didTapMessageBottomLabel(in cell: MessageCollectionViewCell) {
print("Bottom label tapped")
}
}
// MARK: - MessageLabelDelegate
extension ConversationViewController: MessageLabelDelegate {
func didSelectAddress(_ addressComponents: [String: String]) {
print("Address Selected: \(addressComponents)")
}
func didSelectDate(_ date: Date) {
print("Date Selected: \(date)")
}
func didSelectPhoneNumber(_ phoneNumber: String) {
print("Phone Number Selected: \(phoneNumber)")
}
func didSelectURL(_ url: URL) {
print("URL Selected: \(url)")
}
func didSelectTransitInformation(_ transitInformation: [String: String]) {
print("TransitInformation Selected: \(transitInformation)")
}
}
// MARK: - MessageInputBarDelegate
extension ConversationViewController: MessageInputBarDelegate {
func messageInputBar(_ inputBar: MessageInputBar, didPressSendButtonWith text: String) {
// Each NSTextAttachment that contains an image will count as one empty character in the text: String
for component in inputBar.inputTextView.components {
if let image = component as? UIImage {
let imageMessage = MockMessage(image: image, sender: currentSender(), messageId: UUID().uuidString, date: Date())
messageList.append(imageMessage)
messagesCollectionView.insertSections([messageList.count - 1])
} else if let text = component as? String {
let attributedText = NSAttributedString(string: text, attributes: [.font: UIFont.systemFont(ofSize: 15), .foregroundColor: UIColor.blue])
let message = MockMessage(attributedText: attributedText, sender: currentSender(), messageId: UUID().uuidString, date: Date())
messageList.append(message)
messagesCollectionView.insertSections([messageList.count - 1])
}
}
inputBar.inputTextView.text = String()
messagesCollectionView.scrollToBottom()
}
}
+317
View File
@@ -0,0 +1,317 @@
/*
MIT License
Copyright (c) 2017-2018 MessageKit
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import Foundation
public class Lorem {
private static let wordList = [
"alias", "consequatur", "aut", "perferendis", "sit", "voluptatem",
"accusantium", "doloremque", "aperiam", "eaque", "ipsa", "quae", "ab",
"illo", "inventore", "veritatis", "et", "quasi", "architecto",
"beatae", "vitae", "dicta", "sunt", "explicabo", "aspernatur", "aut",
"odit", "aut", "fugit", "sed", "quia", "consequuntur", "magni",
"dolores", "eos", "qui", "ratione", "voluptatem", "sequi", "nesciunt",
"neque", "dolorem", "ipsum", "quia", "dolor", "sit", "amet",
"consectetur", "adipisci", "velit", "sed", "quia", "non", "numquam",
"eius", "modi", "tempora", "incidunt", "ut", "labore", "et", "dolore",
"magnam", "aliquam", "quaerat", "voluptatem", "ut", "enim", "ad",
"minima", "veniam", "quis", "nostrum", "exercitationem", "ullam",
"corporis", "nemo", "enim", "ipsam", "voluptatem", "quia", "voluptas",
"sit", "suscipit", "laboriosam", "nisi", "ut", "aliquid", "ex", "ea",
"commodi", "consequatur", "quis", "autem", "vel", "eum", "iure",
"reprehenderit", "qui", "in", "ea", "voluptate", "velit", "esse",
"quam", "nihil", "molestiae", "et", "iusto", "odio", "dignissimos",
"ducimus", "qui", "blanditiis", "praesentium", "laudantium", "totam",
"rem", "voluptatum", "deleniti", "atque", "corrupti", "quos",
"dolores", "et", "quas", "molestias", "excepturi", "sint",
"occaecati", "cupiditate", "non", "provident", "sed", "ut",
"perspiciatis", "unde", "omnis", "iste", "natus", "error",
"similique", "sunt", "in", "culpa", "qui", "officia", "deserunt",
"mollitia", "animi", "id", "est", "laborum", "et", "dolorum", "fuga",
"et", "harum", "quidem", "rerum", "facilis", "est", "et", "expedita",
"distinctio", "nam", "libero", "tempore", "cum", "soluta", "nobis",
"est", "eligendi", "optio", "cumque", "nihil", "impedit", "quo",
"porro", "quisquam", "est", "qui", "minus", "id", "quod", "maxime",
"placeat", "facere", "possimus", "omnis", "voluptas", "assumenda",
"est", "omnis", "dolor", "repellendus", "temporibus", "autem",
"quibusdam", "et", "aut", "consequatur", "vel", "illum", "qui",
"dolorem", "eum", "fugiat", "quo", "voluptas", "nulla", "pariatur",
"at", "vero", "eos", "et", "accusamus", "officiis", "debitis", "aut",
"rerum", "necessitatibus", "saepe", "eveniet", "ut", "et",
"voluptates", "repudiandae", "sint", "et", "molestiae", "non",
"recusandae", "itaque", "earum", "rerum", "hic", "tenetur", "a",
"sapiente", "delectus", "ut", "aut", "reiciendis", "voluptatibus",
"maiores", "doloribus", "asperiores", "repellat"
]
/**
Return a random word.
- returns: Returns a random word.
*/
public class func word() -> String {
return wordList.random()!
}
/**
Return an array of `count` words.
- parameter count: The number of words to return.
- returns: Returns an array of `count` words.
*/
public class func words(nbWords: Int = 3) -> [String] {
return wordList.random(nbWords)
}
/**
Return a string of `count` words.
- parameter count: The number of words the string should contain.
- returns: Returns a string of `count` words.
*/
public class func words(nbWords: Int = 3) -> String {
return words(nbWords: nbWords).joined(separator: " ")
}
/**
Generate a sentence of `nbWords` words.
- parameter nbWords: The number of words the sentence should contain.
- parameter variable: If `true`, the number of words will vary between
+/- 40% of `nbWords`.
- returns:
*/
public class func sentence(nbWords: Int = 6, variable: Bool = true) -> String {
if nbWords <= 0 {
return ""
}
let result: String = self.words(nbWords: variable ? nbWords.randomize(variation: 40) : nbWords)
return result.firstCapitalized + "."
}
/**
Generate an array of sentences.
- parameter nbSentences: The number of sentences to generate.
- returns: Returns an array of random sentences.
*/
public class func sentences(nbSentences: Int = 3) -> [String] {
return (0..<nbSentences).map { _ in sentence() }
}
/**
Generate a paragraph with `nbSentences` random sentences.
- parameter nbSentences: The number of sentences the paragraph should
contain.
- parameter variable: If `true`, the number of sentences will vary
between +/- 40% of `nbSentences`.
- returns: Returns a paragraph with `nbSentences` random sentences.
*/
public class func paragraph(nbSentences: Int = 3, variable: Bool = true) -> String {
if nbSentences <= 0 {
return ""
}
return sentences(nbSentences: variable ? nbSentences.randomize(variation: 40) : nbSentences).joined(separator: " ")
}
/**
Generate an array of random paragraphs.
- parameter nbParagraphs: The number of paragraphs to generate.
- returns: Returns an array of `nbParagraphs` paragraphs.
*/
public class func paragraphs(nbParagraphs: Int = 3) -> [String] {
return (0..<nbParagraphs).map { _ in paragraph() }
}
/**
Generate a string of random paragrahs.
- parameter nbParagraphs: The number of paragraphs to generate.
- returns: Returns a string of random paragraphs.
*/
public class func paragraphs(nbParagraphs: Int = 3) -> String {
return paragraphs(nbParagraphs: nbParagraphs).joined(separator: "\n\n")
}
/**
Generate a string of at most `maxNbChars` characters.
- parameter maxNbChars: The maximum number of characters the string
should contain.
- returns: Returns a string of at most `maxNbChars` characters.
*/
public class func text(maxNbChars: Int = 200) -> String {
var result: [String] = []
if maxNbChars < 5 {
return ""
} else if maxNbChars < 25 {
while result.count == 0 {
var size = 0
while size < maxNbChars {
let w = (size != 0 ? " " : "") + word()
result.append(w)
size += w.count
}
_ = result.popLast()
}
} else if maxNbChars < 100 {
while result.count == 0 {
var size = 0
while size < maxNbChars {
let s = (size != 0 ? " " : "") + sentence()
result.append(s)
size += s.count
}
_ = result.popLast()
}
} else {
while result.count == 0 {
var size = 0
while size < maxNbChars {
let p = (size != 0 ? "\n" : "") + paragraph()
result.append(p)
size += p.count
}
_ = result.popLast()
}
}
return result.joined(separator: "")
}
}
extension String {
var firstCapitalized: String {
var string = self
string.replaceSubrange(string.startIndex...string.startIndex, with: String(string[string.startIndex]).capitalized)
return string
}
}
public extension Array {
/**
Shuffle the array in-place using the Fisher-Yates algorithm.
*/
public mutating func shuffle() {
for i in 0..<(count - 1) {
let j = Int(arc4random_uniform(UInt32(count - i))) + i
if j != i {
self.swapAt(i, j)
}
}
}
/**
Return a shuffled version of the array using the Fisher-Yates
algorithm.
- returns: Returns a shuffled version of the array.
*/
public func shuffled() -> [Element] {
var list = self
list.shuffle()
return list
}
/**
Return a random element from the array.
- returns: Returns a random element from the array or `nil` if the
array is empty.
*/
public func random() -> Element? {
return (count > 0) ? self.shuffled()[0] : nil
}
/**
Return a random subset of `cnt` elements from the array.
- returns: Returns a random subset of `cnt` elements from the array.
*/
public func random(_ count: Int = 1) -> [Element] {
let result = shuffled()
return (count > result.count) ? result : Array(result[0..<count])
}
}
extension Int {
/**
Return a random number between `min` and `max`.
- note: The maximum value cannot be more than `UInt32.max - 1`
- parameter min: The minimum value of the random value (defaults to `0`).
- parameter max: The maximum value of the random value (defaults to `UInt32.max - 1`)
- returns: Returns a random value between `min` and `max`.
*/
public static func random(min: Int = 0, max: Int = Int.max) -> Int {
precondition(min <= max, "attempt to call random() with min > max")
let diff = UInt(bitPattern: max &- min)
let result = UInt.random(min: 0, max: diff)
return min + Int(bitPattern: result)
}
public func randomize(variation: Int) -> Int {
let multiplier = Double(Int.random(min: 100 - variation, max: 100 + variation)) / 100
let randomized = Double(self) * multiplier
return Int(randomized) + 1
}
}
private extension UInt {
static func random(min: UInt, max: UInt) -> UInt {
precondition(min <= max, "attempt to call random() with min > max")
if min == UInt.min && max == UInt.max {
var result: UInt = 0
arc4random_buf(&result, MemoryLayout.size(ofValue: result))
return result
} else {
let range = max - min + 1
let limit = UInt.max - UInt.max % range
var result: UInt = 0
repeat {
arc4random_buf(&result, MemoryLayout.size(ofValue: result))
} while result >= limit
result = result % range
return min + result
}
}
}
@@ -31,49 +31,34 @@ final internal class SampleData {
private init() {}
let messageTextValues = [
"Ok",
"k",
"lol",
"1-800-555-0000",
"One Infinite Loop Cupertino, CA 95014 This is some extra text that should not be detected.",
"This is an example of the date detector 11/11/2017. April 1st is April Fools Day. Next Friday is not Friday the 13th.",
"https://github.com/SD10",
"Check out this awesome UI library for Chat",
"My favorite things in life don’t cost any money. It’s really clear that the most precious resource we all have is time.",
"""
You know, this iPhone, as a matter of fact, the engine in here is made in America.
And not only are the engines in here made in America, but engines are made in America and are exported.
The glass on this phone is made in Kentucky. And so we've been working for years on doing more and more in the United States.
""",
"""
Remembering that I'll be dead soon is the most important tool I've ever encountered to help me make the big choices in life.
Because almost everything - all external expectations, all pride, all fear of embarrassment or failure -
these things just fall away in the face of death, leaving only what is truly important.
""",
"I think if you do something and it turns out pretty good, then you should go do something else wonderful, not dwell on it for too long. Just figure out what’s next.",
"Price is rarely the most important thing. A cheap product might sell some units. Somebody gets it home and they feel great when they pay the money, but then they get it home and use it and the joy is gone."
]
let system = Sender(id: "000000", displayName: "System")
let nathan = Sender(id: "000001", displayName: "Nathan Tannar")
let steven = Sender(id: "000002", displayName: "Steven Deutsch")
let wu = Sender(id: "000003", displayName: "Wu Zhong")
let dan = Sender(id: "123456", displayName: "Dan Leonard")
let steven = Sender(id: "654321", displayName: "Steven")
let jobs = Sender(id: "000001", displayName: "Steve Jobs")
let cook = Sender(id: "656361", displayName: "Tim Cook")
lazy var senders = [dan, steven, jobs, cook]
lazy var senders = [nathan, steven, wu]
var currentSender: Sender {
return steven
return nathan
}
let messageImages: [UIImage] = [#imageLiteral(resourceName: "Dan-Leonard"), #imageLiteral(resourceName: "Tim-Cook"), #imageLiteral(resourceName: "Steve-Jobs")]
var now = Date()
let messageImages: [UIImage] = [#imageLiteral(resourceName: "img1"), #imageLiteral(resourceName: "img2")]
let messageTypes = ["Text", "Text", "Text", "AttributedText", "Photo", "Video", "Location", "Emoji"]
let messageTypes = ["Text", "Text", "Text", "AttributedText", "Location", "Photo", "Emoji", "Video", "URL", "Phone", "Custom"]
let emojis = [
"👍",
"😂😂😂",
"👋👋👋",
"😱😱😱",
"😃😃😃",
"❤️"
]
let attributes = ["Font1", "Font2", "Font3", "Font4", "Color", "Combo"]
let locations: [CLLocation] = [
CLLocation(latitude: 37.3118, longitude: -122.0312),
CLLocation(latitude: 33.6318, longitude: -100.0386),
@@ -82,22 +67,13 @@ final internal class SampleData {
CLLocation(latitude: 35.3218, longitude: -127.4314),
CLLocation(latitude: 39.3218, longitude: -113.3317)
]
let emojis = [
"👍",
"👋",
"👋👋👋",
"😱😱",
"🎈",
"🇧🇷"
]
func attributedString(with text: String) -> NSAttributedString {
let nsString = NSString(string: text)
var mutableAttributedString = NSMutableAttributedString(string: text)
let randomAttribute = Int(arc4random_uniform(UInt32(attributes.count)))
let range = NSRange(location: 0, length: nsString.length)
switch attributes[randomAttribute] {
case "Font1":
mutableAttributedString.addAttribute(NSAttributedStringKey.font, value: UIFont.preferredFont(forTextStyle: .body), range: range)
@@ -113,7 +89,7 @@ final internal class SampleData {
let msg9String = "Use .attributedText() to add bold, italic, colored text and more..."
let msg9Text = NSString(string: msg9String)
let msg9AttributedText = NSMutableAttributedString(string: String(msg9Text))
msg9AttributedText.addAttribute(NSAttributedStringKey.font, value: UIFont.preferredFont(forTextStyle: .body), range: NSRange(location: 0, length: msg9Text.length))
msg9AttributedText.addAttributes([NSAttributedStringKey.font: UIFont.monospacedDigitSystemFont(ofSize: UIFont.systemFontSize, weight: UIFont.Weight.bold)], range: msg9Text.range(of: ".attributedText()"))
msg9AttributedText.addAttributes([NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)], range: msg9Text.range(of: "bold"))
@@ -123,7 +99,7 @@ final internal class SampleData {
default:
fatalError("Unrecognized attribute for mock message")
}
return NSAttributedString(attributedString: mutableAttributedString)
}
@@ -141,23 +117,24 @@ final internal class SampleData {
}
}
func randomMessage() -> MockMessage {
func randomMessage(isCustomEnabled: Bool, allowedSenders: [Sender]) -> MockMessage {
let randomNumberSender = Int(arc4random_uniform(UInt32(senders.count)))
let randomNumberText = Int(arc4random_uniform(UInt32(messageTextValues.count)))
let randomNumberSender = Int(arc4random_uniform(UInt32(allowedSenders.count)))
let randomNumberImage = Int(arc4random_uniform(UInt32(messageImages.count)))
let randomMessageType = Int(arc4random_uniform(UInt32(messageTypes.count)))
let randomMessageType = Int(arc4random_uniform(UInt32(messageTypes.count - (isCustomEnabled ? 0 : 1))))
let randomNumberLocation = Int(arc4random_uniform(UInt32(locations.count)))
let randomNumberEmoji = Int(arc4random_uniform(UInt32(emojis.count)))
let randomSentance = Lorem.sentence()
let uniqueID = NSUUID().uuidString
let sender = senders[randomNumberSender]
let sender = allowedSenders[randomNumberSender]
let date = dateAddingRandomTime()
switch messageTypes[randomMessageType] {
case "Text":
return MockMessage(text: messageTextValues[randomNumberText], sender: sender, messageId: uniqueID, date: date)
return MockMessage(text: randomSentance, sender: sender, messageId: uniqueID, date: date)
case "AttributedText":
let attributedText = attributedString(with: messageTextValues[randomNumberText])
let attributedText = attributedString(with: randomSentance)
return MockMessage(attributedText: attributedText, sender: senders[randomNumberSender], messageId: uniqueID, date: date)
case "Photo":
let image = messageImages[randomNumberImage]
@@ -165,10 +142,16 @@ final internal class SampleData {
case "Video":
let image = messageImages[randomNumberImage]
return MockMessage(thumbnail: image, sender: sender, messageId: uniqueID, date: date)
case "Location":
return MockMessage(location: locations[randomNumberLocation], sender: sender, messageId: uniqueID, date: date)
case "Emoji":
return MockMessage(emoji: emojis[randomNumberEmoji], sender: sender, messageId: uniqueID, date: date)
case "Location":
return MockMessage(location: locations[randomNumberLocation], sender: sender, messageId: uniqueID, date: date)
case "URL":
return MockMessage(text: "https://github.com/MessageKit", sender: sender, messageId: uniqueID, date: date)
case "Phone":
return MockMessage(text: "123-456-7890", sender: sender, messageId: uniqueID, date: date)
case "Custom":
return MockMessage(custom: "Someone left the conversation", sender: system, messageId: uniqueID, date: date)
default:
fatalError("Unrecognized mock message type")
}
@@ -177,23 +160,45 @@ final internal class SampleData {
func getMessages(count: Int, completion: ([MockMessage]) -> Void) {
var messages: [MockMessage] = []
for _ in 0..<count {
messages.append(randomMessage())
let message = randomMessage(isCustomEnabled: false, allowedSenders: senders)
messages.append(message)
}
completion(messages)
}
func getAdvancedMessages(count: Int, completion: ([MockMessage]) -> Void) {
var messages: [MockMessage] = []
for _ in 0..<count {
let message = randomMessage(isCustomEnabled: true, allowedSenders: senders)
messages.append(message)
}
completion(messages)
}
func getMessages(count: Int, allowedSenders: [Sender], completion: ([MockMessage]) -> Void) {
var messages: [MockMessage] = []
for _ in 0..<count {
let message = randomMessage(isCustomEnabled: false, allowedSenders: allowedSenders)
messages.append(message)
}
completion(messages)
}
func getAvatarFor(sender: Sender) -> Avatar {
let firstName = sender.displayName.components(separatedBy: " ").first
let lastName = sender.displayName.components(separatedBy: " ").first
let initials = "\(firstName?.first ?? "A")\(lastName?.first ?? "A")"
switch sender {
case dan:
return Avatar(image: #imageLiteral(resourceName: "Dan-Leonard"), initials: "DL")
case nathan:
return Avatar(image: #imageLiteral(resourceName: "Nathan-Tannar"), initials: initials)
case steven:
return Avatar(initials: "S")
case jobs:
return Avatar(image: #imageLiteral(resourceName: "Steve-Jobs"), initials: "SJ")
case cook:
return Avatar(image: #imageLiteral(resourceName: "Tim-Cook"))
return Avatar(image: #imageLiteral(resourceName: "Steven-Deutsch"), initials: initials)
case wu:
return Avatar(image: #imageLiteral(resourceName: "Wu-Zhong"), initials: initials)
case system:
return Avatar(image: nil, initials: "SS")
default:
return Avatar()
return Avatar(image: nil, initials: initials)
}
}
@@ -0,0 +1,29 @@
/*
MIT License
Copyright (c) 2017-2018 MessageKit
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import UIKit
extension UIColor {
static let primaryColor = UIColor(red: 69/255, green: 193/255, blue: 89/255, alpha: 1)
}
@@ -0,0 +1,67 @@
/*
MIT License
Copyright (c) 2017-2018 MessageKit
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import UIKit
extension UIViewController {
func updateTitleView(title: String, subtitle: String?, baseColor: UIColor = .white) {
let titleLabel = UILabel(frame: CGRect(x: 0, y: -2, width: 0, height: 0))
titleLabel.backgroundColor = UIColor.clear
titleLabel.textColor = baseColor
titleLabel.font = UIFont.systemFont(ofSize: 15)
titleLabel.text = title
titleLabel.textAlignment = .center
titleLabel.adjustsFontSizeToFitWidth = true
titleLabel.sizeToFit()
let subtitleLabel = UILabel(frame: CGRect(x: 0, y: 18, width: 0, height: 0))
subtitleLabel.textColor = baseColor.withAlphaComponent(0.95)
subtitleLabel.font = UIFont.systemFont(ofSize: 12)
subtitleLabel.text = subtitle
subtitleLabel.textAlignment = .center
subtitleLabel.adjustsFontSizeToFitWidth = true
subtitleLabel.sizeToFit()
let titleView = UIView(frame: CGRect(x: 0, y: 0, width: max(titleLabel.frame.size.width, subtitleLabel.frame.size.width), height: 30))
titleView.addSubview(titleLabel)
if subtitle != nil {
titleView.addSubview(subtitleLabel)
} else {
titleLabel.frame = titleView.frame
}
let widthDiff = subtitleLabel.frame.size.width - titleLabel.frame.size.width
if widthDiff < 0 {
let newX = widthDiff / 2
subtitleLabel.frame.origin.x = abs(newX)
} else {
let newX = widthDiff / 2
titleLabel.frame.origin.x = newX
}
navigationItem.titleView = titleView
}
}
+1 -1
View File
@@ -52,6 +52,6 @@
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
<true/>
</dict>
</plist>
@@ -0,0 +1,67 @@
/*
MIT License
Copyright (c) 2017-2018 MessageKit
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import Foundation
import MessageKit
open class CustomMessagesFlowLayout: MessagesCollectionViewFlowLayout {
open lazy var customMessageSizeCalculator = CustomMessageSizeCalculator(layout: self)
open override func cellSizeCalculatorForItem(at indexPath: IndexPath) -> CellSizeCalculator {
// if isSectionReservedForTypingBubble(indexPath.section) {
// return typingMessageSizeCalculator
// }
let message = messagesDataSource.messageForItem(at: indexPath, in: messagesCollectionView)
if case .custom = message.kind {
return customMessageSizeCalculator
}
return super.cellSizeCalculatorForItem(at: indexPath)
}
open override func messageSizeCalculators() -> [MessageSizeCalculator] {
var superCalculators = super.messageSizeCalculators()
// Append any of your custom `MessageSizeCalculator` if you wish for the convenience
// functions to work such as `setMessageIncoming...` or `setMessageOutgoing...`
superCalculators.append(customMessageSizeCalculator)
return superCalculators
}
}
open class CustomMessageSizeCalculator: MessageSizeCalculator {
public override init(layout: MessagesCollectionViewFlowLayout? = nil) {
super.init()
self.layout = layout
}
open override func sizeForItem(at indexPath: IndexPath) -> CGSize {
guard let layout = layout else { return .zero }
let collectionViewWidth = layout.collectionView?.bounds.width ?? 0
let contentInset = layout.collectionView?.contentInset ?? .zero
let inset = layout.sectionInset.left + layout.sectionInset.right + contentInset.left + contentInset.right
return CGSize(width: collectionViewWidth - inset, height: 44)
}
}
@@ -26,7 +26,7 @@ import Foundation
import CoreLocation
import MessageKit
private struct MockLocationItem: LocationItem {
private struct CoordinateItem: LocationItem {
var location: CLLocation
var size: CGSize
@@ -38,7 +38,7 @@ private struct MockLocationItem: LocationItem {
}
private struct MockMediaItem: MediaItem {
private struct ImageMediaItem: MediaItem {
var url: URL?
var image: UIImage?
@@ -66,6 +66,10 @@ internal struct MockMessage: MessageType {
self.messageId = messageId
self.sentDate = date
}
init(custom: Any?, sender: Sender, messageId: String, date: Date) {
self.init(kind: .custom(custom), sender: sender, messageId: messageId, date: date)
}
init(text: String, sender: Sender, messageId: String, date: Date) {
self.init(kind: .text(text), sender: sender, messageId: messageId, date: date)
@@ -76,17 +80,17 @@ internal struct MockMessage: MessageType {
}
init(image: UIImage, sender: Sender, messageId: String, date: Date) {
let mediaItem = MockMediaItem(image: image)
let mediaItem = ImageMediaItem(image: image)
self.init(kind: .photo(mediaItem), sender: sender, messageId: messageId, date: date)
}
init(thumbnail: UIImage, sender: Sender, messageId: String, date: Date) {
let mediaItem = MockMediaItem(image: thumbnail)
let mediaItem = ImageMediaItem(image: thumbnail)
self.init(kind: .video(mediaItem), sender: sender, messageId: messageId, date: date)
}
init(location: CLLocation, sender: Sender, messageId: String, date: Date) {
let locationItem = MockLocationItem(location: location)
let locationItem = CoordinateItem(location: location)
self.init(kind: .location(locationItem), sender: sender, messageId: messageId, date: date)
}
+85
View File
@@ -0,0 +1,85 @@
/*
MIT License
Copyright (c) 2017-2018 MessageKit
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import UIKit
import MessageKit
final class MockSocket {
static var shared = MockSocket()
private var timer: Timer?
private var queuedMessage: MockMessage?
private var onNewMessageCode: ((MockMessage) -> Void)?
private var onTypingStatusCode: (() -> Void)?
private var connectedUsers: [Sender] = []
private init() {}
@discardableResult
func connect(with senders: [Sender]) -> Self {
disconnect()
connectedUsers = senders
timer = Timer.scheduledTimer(timeInterval: 2.5, target: self, selector: #selector(handleTimer), userInfo: nil, repeats: true)
return self
}
@discardableResult
func disconnect() -> Self {
timer?.invalidate()
timer = nil
onTypingStatusCode = nil
onNewMessageCode = nil
return self
}
@discardableResult
func onNewMessage(code: @escaping (MockMessage) -> Void) -> Self {
onNewMessageCode = code
return self
}
@discardableResult
func onTypingStatus(code: @escaping () -> Void) -> Self {
onTypingStatusCode = code
return self
}
@objc
private func handleTimer() {
if let message = queuedMessage {
onNewMessageCode?(message)
queuedMessage = nil
} else {
let sender = arc4random_uniform(1) % 2 == 0 ? connectedUsers.first! : connectedUsers.last!
queuedMessage = MockMessage(text: Lorem.sentence(), sender: sender, messageId: UUID().uuidString, date: Date())
onTypingStatusCode?()
}
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
/*
MIT License
Copyright (c) 2017 MessageKit
Copyright (c) 2017-2018 MessageKit
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -0,0 +1,363 @@
/*
MIT License
Copyright (c) 2017-2018 MessageKit
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import UIKit
import MessageKit
import MapKit
final class AdvancedExampleViewController: ChatViewController {
let outgoingAvatarOverlap: CGFloat = 17.5
override func viewDidLoad() {
messagesCollectionView = MessagesCollectionView(frame: .zero, collectionViewLayout: CustomMessagesFlowLayout())
messagesCollectionView.register(CustomCell.self)
super.viewDidLoad()
updateTitleView(title: "MessageKit", subtitle: "2 Online")
// Customize the typing bubble! These are the default values
// typingBubbleBackgroundColor = UIColor(red: 230/255, green: 230/255, blue: 230/255, alpha: 1)
// typingBubbleDotColor = .lightGray
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
MockSocket.shared.connect(with: [SampleData.shared.steven, SampleData.shared.wu])
.onTypingStatus { [weak self] in
self?.setTypingIndicatorHidden(false)
}.onNewMessage { [weak self] message in
self?.setTypingIndicatorHidden(true, performUpdates: {
// self?.insertMessage(message)
})
self?.insertMessage(message)
}
}
override func loadFirstMessages() {
DispatchQueue.global(qos: .userInitiated).async {
let count = UserDefaults.standard.mockMessagesCount()
SampleData.shared.getAdvancedMessages(count: count) { messages in
DispatchQueue.main.async {
self.messageList = messages
self.messagesCollectionView.reloadData()
self.messagesCollectionView.scrollToBottom()
}
}
}
}
override func loadMoreMessages() {
DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + 1) {
SampleData.shared.getAdvancedMessages(count: 20) { messages in
DispatchQueue.main.async {
self.messageList.insert(contentsOf: messages, at: 0)
self.messagesCollectionView.reloadDataAndKeepOffset()
self.refreshControl.endRefreshing()
}
}
}
}
override func configureMessageCollectionView() {
super.configureMessageCollectionView()
let layout = messagesCollectionView.collectionViewLayout as? MessagesCollectionViewFlowLayout
layout?.sectionInset = UIEdgeInsets(top: 1, left: 8, bottom: 1, right: 8)
// Hide the outgoing avatar and adjust the label alignment to line up with the messages
layout?.setMessageOutgoingAvatarSize(.zero)
layout?.setMessageOutgoingMessageTopLabelAlignment(LabelAlignment(textAlignment: .right, textInsets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 8)))
layout?.setMessageOutgoingMessageBottomLabelAlignment(LabelAlignment(textAlignment: .right, textInsets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 8)))
// Set outgoing avatar to overlap with the message bubble
layout?.setMessageIncomingMessageTopLabelAlignment(LabelAlignment(textAlignment: .left, textInsets: UIEdgeInsets(top: 0, left: 18, bottom: outgoingAvatarOverlap, right: 0)))
layout?.setMessageIncomingAvatarSize(CGSize(width: 30, height: 30))
layout?.setMessageIncomingMessagePadding(UIEdgeInsets(top: -outgoingAvatarOverlap, left: -18, bottom: outgoingAvatarOverlap, right: 18))
messagesCollectionView.messagesLayoutDelegate = self
messagesCollectionView.messagesDisplayDelegate = self
}
override func configureMessageInputBar() {
super.configureMessageInputBar()
messageInputBar.isTranslucent = true
messageInputBar.separatorLine.isHidden = true
messageInputBar.inputTextView.tintColor = .primaryColor
messageInputBar.inputTextView.backgroundColor = UIColor(red: 245/255, green: 245/255, blue: 245/255, alpha: 1)
messageInputBar.inputTextView.placeholderTextColor = UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1)
messageInputBar.inputTextView.textContainerInset = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 36)
messageInputBar.inputTextView.placeholderLabelInsets = UIEdgeInsets(top: 8, left: 20, bottom: 8, right: 36)
messageInputBar.inputTextView.layer.borderColor = UIColor(red: 200/255, green: 200/255, blue: 200/255, alpha: 1).cgColor
messageInputBar.inputTextView.layer.borderWidth = 1.0
messageInputBar.inputTextView.layer.cornerRadius = 16.0
messageInputBar.inputTextView.layer.masksToBounds = true
messageInputBar.inputTextView.scrollIndicatorInsets = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
messageInputBar.setRightStackViewWidthConstant(to: 36, animated: false)
messageInputBar.sendButton.imageView?.backgroundColor = UIColor(white: 0.85, alpha: 1)
messageInputBar.sendButton.contentEdgeInsets = UIEdgeInsets(top: 2, left: 2, bottom: 2, right: 2)
messageInputBar.sendButton.setSize(CGSize(width: 36, height: 36), animated: false)
messageInputBar.sendButton.image = #imageLiteral(resourceName: "ic_up")
messageInputBar.sendButton.title = nil
messageInputBar.sendButton.imageView?.layer.cornerRadius = 16
messageInputBar.textViewPadding.right = -38
let charCountButton = InputBarButtonItem()
.configure {
$0.title = "0/140"
$0.contentHorizontalAlignment = .right
$0.setTitleColor(UIColor(white: 0.6, alpha: 1), for: .normal)
$0.titleLabel?.font = UIFont.systemFont(ofSize: 10, weight: .bold)
$0.setSize(CGSize(width: 50, height: 25), animated: false)
}.onTextViewDidChange { (item, textView) in
item.title = "\(textView.text.count)/140"
let isOverLimit = textView.text.count > 140
item.messageInputBar?.shouldManageSendButtonEnabledState = !isOverLimit // Disable automated management when over limit
item.messageInputBar?.sendButton.isEnabled = !isOverLimit
let color = isOverLimit ? .red : UIColor(white: 0.6, alpha: 1)
item.setTitleColor(color, for: .normal)
}
let bottomItems = [makeButton(named: "ic_at"), makeButton(named: "ic_hashtag"), makeButton(named: "ic_library"), .flexibleSpace, charCountButton]
messageInputBar.textViewPadding.bottom = 8
messageInputBar.setStackViewItems(bottomItems, forStack: .bottom, animated: false)
// This just adds some more flare
messageInputBar.sendButton
.onEnabled { item in
UIView.animate(withDuration: 0.3, animations: {
item.imageView?.backgroundColor = .primaryColor
})
}.onDisabled { item in
UIView.animate(withDuration: 0.3, animations: {
item.imageView?.backgroundColor = UIColor(white: 0.85, alpha: 1)
})
}
}
// MARK: - Helpers
func isTimeLabelVisible(at indexPath: IndexPath) -> Bool {
return indexPath.section % 3 == 0 && !isPreviousMessageSameSender(at: indexPath)
}
func isPreviousMessageSameSender(at indexPath: IndexPath) -> Bool {
guard indexPath.section - 1 >= 0 else { return false }
return messageList[indexPath.section].sender == messageList[indexPath.section - 1].sender
}
func isNextMessageSameSender(at indexPath: IndexPath) -> Bool {
guard indexPath.section + 1 < messageList.count else { return false }
return messageList[indexPath.section].sender == messageList[indexPath.section + 1].sender
}
func setTypingIndicatorHidden(_ isHidden: Bool, performUpdates updates: (() -> Void)? = nil) {
updateTitleView(title: "MessageKit", subtitle: isHidden ? "2 Online" : "Typing...")
// setTypingBubbleHidden(isHidden, animated: true, whilePerforming: updates) { [weak self] (_) in
// if self?.isLastSectionVisible() == true {
// self?.messagesCollectionView.scrollToBottom(animated: true)
// }
// }
messagesCollectionView.scrollToBottom(animated: true)
}
private func makeButton(named: String) -> InputBarButtonItem {
return InputBarButtonItem()
.configure {
$0.spacing = .fixed(10)
$0.image = UIImage(named: named)?.withRenderingMode(.alwaysTemplate)
$0.setSize(CGSize(width: 25, height: 25), animated: false)
$0.tintColor = UIColor(white: 0.8, alpha: 1)
}.onSelected {
$0.tintColor = .primaryColor
}.onDeselected {
$0.tintColor = UIColor(white: 0.8, alpha: 1)
}.onTouchUpInside { _ in
print("Item Tapped")
}
}
// MARK: - UICollectionViewDataSource
open override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let messagesDataSource = messagesCollectionView.messagesDataSource else {
fatalError("Ouch. nil data source for messages")
}
// guard !isSectionReservedForTypingBubble(indexPath.section) else {
// return super.collectionView(collectionView, cellForItemAt: indexPath)
// }
let message = messagesDataSource.messageForItem(at: indexPath, in: messagesCollectionView)
if case .custom = message.kind {
let cell = messagesCollectionView.dequeueReusableCell(CustomCell.self, for: indexPath)
cell.configure(with: message, at: indexPath, and: messagesCollectionView)
return cell
}
return super.collectionView(collectionView, cellForItemAt: indexPath)
}
// MARK: - MessagesDataSource
override func cellTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
if isTimeLabelVisible(at: indexPath) {
return NSAttributedString(string: MessageKitDateFormatter.shared.string(from: message.sentDate), attributes: [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 10), NSAttributedStringKey.foregroundColor: UIColor.darkGray])
}
return nil
}
override func messageTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
if !isPreviousMessageSameSender(at: indexPath) {
let name = message.sender.displayName
return NSAttributedString(string: name, attributes: [NSAttributedStringKey.font: UIFont.preferredFont(forTextStyle: .caption1)])
}
return nil
}
override func messageBottomLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
if !isNextMessageSameSender(at: indexPath) && isFromCurrentSender(message: message) {
return NSAttributedString(string: "Delivered", attributes: [NSAttributedStringKey.font: UIFont.preferredFont(forTextStyle: .caption1)])
}
return nil
}
}
// MARK: - MessagesDisplayDelegate
extension AdvancedExampleViewController: MessagesDisplayDelegate {
// MARK: - Text Messages
func textColor(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> UIColor {
return isFromCurrentSender(message: message) ? .white : .darkText
}
func detectorAttributes(for detector: DetectorType, and message: MessageType, at indexPath: IndexPath) -> [NSAttributedStringKey: Any] {
return MessageLabel.defaultAttributes
}
func enabledDetectors(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> [DetectorType] {
return [.url, .address, .phoneNumber, .date, .transitInformation]
}
// MARK: - All Messages
func backgroundColor(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> UIColor {
return isFromCurrentSender(message: message) ? .primaryColor : UIColor(red: 230/255, green: 230/255, blue: 230/255, alpha: 1)
}
func messageStyle(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageStyle {
var corners: UIRectCorner = []
if isFromCurrentSender(message: message) {
corners.formUnion(.topLeft)
corners.formUnion(.bottomLeft)
if !isPreviousMessageSameSender(at: indexPath) {
corners.formUnion(.topRight)
}
if !isNextMessageSameSender(at: indexPath) {
corners.formUnion(.bottomRight)
}
} else {
corners.formUnion(.topRight)
corners.formUnion(.bottomRight)
if !isPreviousMessageSameSender(at: indexPath) {
corners.formUnion(.topLeft)
}
if !isNextMessageSameSender(at: indexPath) {
corners.formUnion(.bottomLeft)
}
}
return .custom { view in
let radius: CGFloat = 16
let path = UIBezierPath(roundedRect: view.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
view.layer.mask = mask
}
}
func configureAvatarView(_ avatarView: AvatarView, for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) {
let avatar = SampleData.shared.getAvatarFor(sender: message.sender)
avatarView.set(avatar: avatar)
avatarView.isHidden = isNextMessageSameSender(at: indexPath)
avatarView.layer.borderWidth = 2
avatarView.layer.borderColor = UIColor.primaryColor.cgColor
}
// MARK: - Location Messages
func annotationViewForLocation(message: MessageType, at indexPath: IndexPath, in messageCollectionView: MessagesCollectionView) -> MKAnnotationView? {
let annotationView = MKAnnotationView(annotation: nil, reuseIdentifier: nil)
let pinImage = #imageLiteral(resourceName: "ic_map_marker")
annotationView.image = pinImage
annotationView.centerOffset = CGPoint(x: 0, y: -pinImage.size.height / 2)
return annotationView
}
func animationBlockForLocation(message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> ((UIImageView) -> Void)? {
return { view in
view.layer.transform = CATransform3DMakeScale(2, 2, 2)
UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0, options: [], animations: {
view.layer.transform = CATransform3DIdentity
}, completion: nil)
}
}
func snapshotOptionsForLocation(message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> LocationMessageSnapshotOptions {
return LocationMessageSnapshotOptions(showsBuildings: true, showsPointsOfInterest: true, span: MKCoordinateSpan(latitudeDelta: 10, longitudeDelta: 10))
}
}
// MARK: - MessagesLayoutDelegate
extension AdvancedExampleViewController: MessagesLayoutDelegate {
func cellTopLabelHeight(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGFloat {
if isTimeLabelVisible(at: indexPath) {
return 18
}
return 0
}
func messageTopLabelHeight(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGFloat {
if isFromCurrentSender(message: message) {
return !isPreviousMessageSameSender(at: indexPath) ? 20 : 0
} else {
return !isPreviousMessageSameSender(at: indexPath) ? (20 + outgoingAvatarOverlap) : 0
}
}
func messageBottomLabelHeight(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGFloat {
return (!isNextMessageSameSender(at: indexPath) && isFromCurrentSender(message: message)) ? 16 : 0
}
}
@@ -0,0 +1,117 @@
/*
MIT License
Copyright (c) 2017-2018 MessageKit
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import UIKit
import MapKit
import MessageKit
final class BasicExampleViewController: ChatViewController {
override func configureMessageCollectionView() {
super.configureMessageCollectionView()
messagesCollectionView.messagesLayoutDelegate = self
messagesCollectionView.messagesDisplayDelegate = self
}
}
// MARK: - MessagesDisplayDelegate
extension BasicExampleViewController: MessagesDisplayDelegate {
// MARK: - Text Messages
func textColor(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> UIColor {
return isFromCurrentSender(message: message) ? .white : .darkText
}
func detectorAttributes(for detector: DetectorType, and message: MessageType, at indexPath: IndexPath) -> [NSAttributedStringKey: Any] {
return MessageLabel.defaultAttributes
}
func enabledDetectors(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> [DetectorType] {
return [.url, .address, .phoneNumber, .date, .transitInformation]
}
// MARK: - All Messages
func backgroundColor(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> UIColor {
return isFromCurrentSender(message: message) ? .primaryColor : UIColor(red: 230/255, green: 230/255, blue: 230/255, alpha: 1)
}
func messageStyle(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageStyle {
let tail: MessageStyle.TailCorner = isFromCurrentSender(message: message) ? .bottomRight : .bottomLeft
return .bubbleTail(tail, .curved)
}
func configureAvatarView(_ avatarView: AvatarView, for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) {
let avatar = SampleData.shared.getAvatarFor(sender: message.sender)
avatarView.set(avatar: avatar)
}
// MARK: - Location Messages
func annotationViewForLocation(message: MessageType, at indexPath: IndexPath, in messageCollectionView: MessagesCollectionView) -> MKAnnotationView? {
let annotationView = MKAnnotationView(annotation: nil, reuseIdentifier: nil)
let pinImage = #imageLiteral(resourceName: "ic_map_marker")
annotationView.image = pinImage
annotationView.centerOffset = CGPoint(x: 0, y: -pinImage.size.height / 2)
return annotationView
}
func animationBlockForLocation(message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> ((UIImageView) -> Void)? {
return { view in
view.layer.transform = CATransform3DMakeScale(2, 2, 2)
UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0, options: [], animations: {
view.layer.transform = CATransform3DIdentity
}, completion: nil)
}
}
func snapshotOptionsForLocation(message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> LocationMessageSnapshotOptions {
return LocationMessageSnapshotOptions(showsBuildings: true, showsPointsOfInterest: true, span: MKCoordinateSpan(latitudeDelta: 10, longitudeDelta: 10))
}
}
// MARK: - MessagesLayoutDelegate
extension BasicExampleViewController: MessagesLayoutDelegate {
func cellTopLabelHeight(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGFloat {
return 18
}
func messageTopLabelHeight(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGFloat {
return 20
}
func messageBottomLabelHeight(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGFloat {
return 16
}
}
@@ -0,0 +1,257 @@
/*
MIT License
Copyright (c) 2017-2018 MessageKit
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import UIKit
import MessageKit
/// A base class for the example controllers
class ChatViewController: MessagesViewController, MessagesDataSource {
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
var messageList: [MockMessage] = []
let refreshControl = UIRefreshControl()
let formatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .medium
return formatter
}()
override func viewDidLoad() {
super.viewDidLoad()
configureMessageCollectionView()
configureMessageInputBar()
loadFirstMessages()
title = "MessageKit"
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
MockSocket.shared.connect(with: [SampleData.shared.steven, SampleData.shared.wu])
.onNewMessage { [weak self] message in
self?.insertMessage(message)
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
MockSocket.shared.disconnect()
}
func loadFirstMessages() {
DispatchQueue.global(qos: .userInitiated).async {
let count = UserDefaults.standard.mockMessagesCount()
SampleData.shared.getMessages(count: count) { messages in
DispatchQueue.main.async {
self.messageList = messages
self.messagesCollectionView.reloadData()
self.messagesCollectionView.scrollToBottom()
}
}
}
}
@objc
func loadMoreMessages() {
DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + 1) {
SampleData.shared.getMessages(count: 20) { messages in
DispatchQueue.main.async {
self.messageList.insert(contentsOf: messages, at: 0)
self.messagesCollectionView.reloadDataAndKeepOffset()
self.refreshControl.endRefreshing()
}
}
}
}
func configureMessageCollectionView() {
messagesCollectionView.messagesDataSource = self
messagesCollectionView.messageCellDelegate = self
scrollsToBottomOnKeybordBeginsEditing = true // default false
maintainPositionOnKeyboardFrameChanged = true // default false
messagesCollectionView.addSubview(refreshControl)
refreshControl.addTarget(self, action: #selector(loadMoreMessages), for: .valueChanged)
}
func configureMessageInputBar() {
messageInputBar.delegate = self
messageInputBar.inputTextView.tintColor = .primaryColor
messageInputBar.sendButton.tintColor = .primaryColor
}
// MARK: - Helpers
func insertMessage(_ message: MockMessage) {
messageList.append(message)
// Reload last section to update header/footer labels and insert a new one
messagesCollectionView.performBatchUpdates({
messagesCollectionView.insertSections([messageList.count - 1])
if messageList.count >= 2 {
messagesCollectionView.reloadSections([messageList.count - 2])
}
}, completion: { [weak self] _ in
if self?.isLastSectionVisible() == true {
self?.messagesCollectionView.scrollToBottom(animated: true)
}
})
}
func isLastSectionVisible() -> Bool {
guard !messageList.isEmpty else { return false }
let lastIndexPath = IndexPath(item: 0, section: messageList.count - 1)
let frame = messagesCollectionView.layoutAttributesForItem(at: lastIndexPath)?.frame ?? .zero
var rect = messagesCollectionView.convert(frame, to: view)
// substract 100 to make the "visible" area of a cell bigger
rect.origin.y -= 100
var visibleRect = CGRect(x: messagesCollectionView.bounds.origin.x, y: messagesCollectionView.bounds.origin.y, width:
messagesCollectionView.bounds.size.width, height:
messagesCollectionView.bounds.size.height - messagesCollectionView.contentInset.bottom)
visibleRect = messagesCollectionView.convert(visibleRect, to: view)
return visibleRect.contains(rect)
}
// MARK: - MessagesDataSource
func currentSender() -> Sender {
return SampleData.shared.currentSender
}
func numberOfSections(in messagesCollectionView: MessagesCollectionView) -> Int {
return messageList.count
}
func messageForItem(at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageType {
return messageList[indexPath.section]
}
func cellTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
if indexPath.section % 3 == 0 {
return NSAttributedString(string: MessageKitDateFormatter.shared.string(from: message.sentDate), attributes: [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 10), NSAttributedStringKey.foregroundColor: UIColor.darkGray])
}
return nil
}
func messageTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
let name = message.sender.displayName
return NSAttributedString(string: name, attributes: [NSAttributedStringKey.font: UIFont.preferredFont(forTextStyle: .caption1)])
}
func messageBottomLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
let dateString = formatter.string(from: message.sentDate)
return NSAttributedString(string: dateString, attributes: [NSAttributedStringKey.font: UIFont.preferredFont(forTextStyle: .caption2)])
}
}
// MARK: - MessageCellDelegate
extension ChatViewController: MessageCellDelegate {
func didTapAvatar(in cell: MessageCollectionViewCell) {
print("Avatar tapped")
}
func didTapMessage(in cell: MessageCollectionViewCell) {
print("Message tapped")
}
func didTapCellTopLabel(in cell: MessageCollectionViewCell) {
print("Top cell label tapped")
}
func didTapMessageTopLabel(in cell: MessageCollectionViewCell) {
print("Top message label tapped")
}
func didTapMessageBottomLabel(in cell: MessageCollectionViewCell) {
print("Bottom label tapped")
}
}
// MARK: - MessageLabelDelegate
extension ChatViewController: MessageLabelDelegate {
func didSelectAddress(_ addressComponents: [String: String]) {
print("Address Selected: \(addressComponents)")
}
func didSelectDate(_ date: Date) {
print("Date Selected: \(date)")
}
func didSelectPhoneNumber(_ phoneNumber: String) {
print("Phone Number Selected: \(phoneNumber)")
}
func didSelectURL(_ url: URL) {
print("URL Selected: \(url)")
}
func didSelectTransitInformation(_ transitInformation: [String: String]) {
print("TransitInformation Selected: \(transitInformation)")
}
}
// MARK: - MessageInputBarDelegate
extension ChatViewController: MessageInputBarDelegate {
func messageInputBar(_ inputBar: MessageInputBar, didPressSendButtonWith text: String) {
for component in inputBar.inputTextView.components {
if let str = component as? String {
let message = MockMessage(text: str, sender: currentSender(), messageId: UUID().uuidString, date: Date())
insertMessage(message)
} else if let img = component as? UIImage {
let message = MockMessage(image: img, sender: currentSender(), messageId: UUID().uuidString, date: Date())
insertMessage(message)
}
}
inputBar.inputTextView.text = String()
messagesCollectionView.scrollToBottom(animated: true)
}
}
@@ -26,18 +26,20 @@ import UIKit
import MessageKit
import SafariServices
final internal class InboxViewController: UITableViewController {
final internal class LaunchViewController: UITableViewController {
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
let cells = ["Example", "Settings", "Source Code", "Contributors"]
let cells = ["Basic Example", "Advanced Example", "Embedded Example", "Settings", "Source Code", "Contributors"]
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
title = "MessageKit"
navigationController?.navigationBar.tintColor = .white
navigationController?.navigationBar.barTintColor = UIColor(red: 69/255, green: 193/255, blue: 89/255, alpha: 1)
navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 20, weight: UIFont.Weight.bold) ]
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.tableFooterView = UIView()
}
@@ -46,7 +48,6 @@ final internal class InboxViewController: UITableViewController {
super.viewWillAppear(animated)
if #available(iOS 11.0, *) {
navigationController?.navigationBar.prefersLargeTitles = true
navigationController?.navigationBar.largeTitleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
}
}
@@ -75,21 +76,31 @@ final internal class InboxViewController: UITableViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = cells[indexPath.row]
switch cell {
case "Example":
navigationController?.pushViewController(ConversationViewController(), animated: true)
case "Basic Example":
navigationController?.pushViewController(BasicExampleViewController(), animated: true)
case "Advanced Example":
navigationController?.pushViewController(AdvancedExampleViewController(), animated: true)
case "Embedded Example":
navigationController?.pushViewController(MessageContainerController(), animated: true)
case "Settings":
navigationController?.pushViewController(SettingsViewController(), animated: true)
case "Source Code":
guard let url = URL(string: "https://github.com/MessageKit/MessageKit") else { return }
let webViewController = SFSafariViewController(url: url)
present(webViewController, animated: true, completion: nil)
openURL(url)
case "Contributors":
guard let url = URL(string: "https://github.com/orgs/MessageKit/teams/contributors/members") else { return }
let webViewController = SFSafariViewController(url: url)
present(webViewController, animated: true, completion: nil)
openURL(url)
default:
assertionFailure("You need to impliment the action for this cell: \(cell)")
return
}
}
func openURL(_ url: URL) {
let webViewController = SFSafariViewController(url: url)
if #available(iOS 10.0, *) {
webViewController.preferredControlTintColor = .primaryColor
}
present(webViewController, animated: true, completion: nil)
}
}
@@ -0,0 +1,88 @@
/*
MIT License
Copyright (c) 2017-2018 MessageKit
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import UIKit
import MapKit
final class MessageContainerController: UIViewController {
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
let mapView = MKMapView()
let bannerView: UIView = {
let view = UIView()
view.backgroundColor = .primaryColor
view.alpha = 0.7
return view
}()
let conversationViewController = BasicExampleViewController()
/// Required for the `MessageInputBar` to be visible
override var canBecomeFirstResponder: Bool {
return conversationViewController.canBecomeFirstResponder
}
/// Required for the `MessageInputBar` to be visible
override var inputAccessoryView: UIView? {
return conversationViewController.inputAccessoryView
}
override func viewDidLoad() {
super.viewDidLoad()
/// Add the `ConversationViewController` as a child view controller
conversationViewController.willMove(toParentViewController: self)
self.addChildViewController(conversationViewController)
view.addSubview(conversationViewController.view)
conversationViewController.didMove(toParentViewController: self)
view.addSubview(mapView)
view.addSubview(bannerView)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.navigationBar.isTranslucent = true
navigationController?.navigationBar.barTintColor = .clear
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.navigationBar.isTranslucent = false
navigationController?.navigationBar.barTintColor = .primaryColor
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let headerHeight: CGFloat = 200
mapView.frame = CGRect(origin: .zero, size: CGSize(width: view.bounds.width, height: headerHeight))
bannerView.frame = CGRect(origin: .zero, size: CGSize(width: view.bounds.width, height: headerHeight))
conversationViewController.view.frame = CGRect(x: 0, y: headerHeight, width: view.bounds.width, height: view.bounds.height - headerHeight)
}
}
@@ -0,0 +1,67 @@
/*
MIT License
Copyright (c) 2017-2018 MessageKit
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import UIKit
final class NavigationController: UINavigationController {
override var preferredStatusBarStyle: UIStatusBarStyle {
return viewControllers.last?.preferredStatusBarStyle ?? .lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
navigationBar.isTranslucent = false
navigationBar.tintColor = .white
navigationBar.barTintColor = .primaryColor
navigationBar.titleTextAttributes = [.foregroundColor: UIColor.white]
if #available(iOS 11.0, *) {
navigationBar.largeTitleTextAttributes = [.foregroundColor: UIColor.white]
}
navigationBar.shadowImage = UIImage()
navigationBar.setBackgroundImage(UIImage(), for: .default)
view.backgroundColor = .primaryColor
}
func setAppearanceStyle(to style: UIStatusBarStyle) {
if style == .default {
navigationBar.shadowImage = UIImage()
navigationBar.barTintColor = .primaryColor
navigationBar.tintColor = .white
navigationBar.titleTextAttributes = [.foregroundColor: UIColor.white]
if #available(iOS 11.0, *) {
navigationBar.largeTitleTextAttributes = [.foregroundColor: UIColor.white]
}
} else if style == .lightContent {
navigationBar.shadowImage = nil
navigationBar.barTintColor = .white
navigationBar.tintColor = UIColor(red: 0, green: 0.5, blue: 1, alpha: 1)
navigationBar.titleTextAttributes = [.foregroundColor: UIColor.black]
if #available(iOS 11.0, *) {
navigationBar.largeTitleTextAttributes = [.foregroundColor: UIColor.black]
}
}
}
}
@@ -31,6 +31,10 @@ final internal class SettingsViewController: UITableViewController {
var selectedMockMessagesCount: Int = 20
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
// MARK: - Picker
var messagesPicker = UIPickerView()
@@ -69,7 +73,7 @@ final internal class SettingsViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(TextFieldTableViewCell.self, forCellReuseIdentifier: TextFieldTableViewCell.identifier)
tableView.tableFooterView = UIView()
configurePickerView()
configureToolbar()
}
+64
View File
@@ -0,0 +1,64 @@
/*
MIT License
Copyright (c) 2017-2018 MessageKit
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import UIKit
import MessageKit
open class CustomCell: UICollectionViewCell {
let label = UILabel()
public override init(frame: CGRect) {
super.init(frame: frame)
setupSubviews()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupSubviews()
}
open func setupSubviews() {
contentView.addSubview(label)
label.textAlignment = .center
label.font = UIFont.italicSystemFont(ofSize: 13)
}
open override func layoutSubviews() {
super.layoutSubviews()
label.frame = contentView.bounds
}
open func configure(with message: MessageType, at indexPath: IndexPath, and messagesCollectionView: MessagesCollectionView) {
// Do stuff
switch message.kind {
case .custom(let data):
guard let systemMessage = data as? String else { return }
label.text = systemMessage
default:
break
}
}
}
@@ -1,7 +1,7 @@
/*
MIT License
Copyright (c) 2017 MessageKit
Copyright (c) 2017-2018 MessageKit
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal