主要代码:
1.表情点击事件
void emotionda1_EmojiClicked(string name)
{
EmojiTextAttachment emojiTextAttachment = new EmojiTextAttachment ();
emojiTextAttachment.emojiTag = new NSString(name);
string plistPath = NSBundle.MainBundle.PathForResource ("Emoji", "plist");
NSDictionary emojiPlistDic = new NSDictionary(plistPath);
string imgpath=NSBundle.MainBundle.PathForResource ("Emoji/"+emojiPlistDic[name].ToString(), "png");
UIImage emojiImage = UIImage.FromBundle (imgpath);
UIFont font = UIFont.SystemFontOfSize (15);
CGSize emojiSize = new CGSize (font.LineHeight,font.LineHeight);
UIGraphics.BeginImageContextWithOptions (emojiSize, false,(nfloat)0);
emojiImage.Draw (new CGRect (0, 0, emojiSize.Width, emojiSize.Height));
UIImage resizedImage = UIGraphics.GetImageFromCurrentImageContext ();
UIGraphics.EndImageContext ();
emojiTextAttachment.Image = resizedImage;
emojiTextAttachment.Bounds = new CGRect (0, -4, emojiSize.Width, emojiSize.Height);
NSAttributedString rep = NSAttributedString.CreateFrom (emojiTextAttachment);
txtInputBox.TextStorage.Insert(rep,txtInputBox.SelectedRange.Location);
txtInputBox.SelectedRange = new NSRange (txtInputBox.SelectedRange.Location + 1, txtInputBox.SelectedRange.Length);
}
2.Textview代理 获取输入的文本
public class MyTextViewDelegate:UITextViewDelegate
{
Chat chat;
int bases = 0;
NSMutableString plainString = new NSMutableString ();
public MyTextViewDelegate(Chat chat)
{
this.chat=chat;
}
public override bool ShouldBeginEditing (UITextView textView)
{
return true;
}
public override bool ShouldChangeText (UITextView textView, NSRange range, string text)
{
if (text.Contains("\n")) {
NSRange textRange = new NSRange (0, textView.AttributedText.Length);
plainString.SetString(new NSString(textView.Text.ToString()));
textView.TextStorage.EnumerateAttributes(textRange,NSAttributedStringEnumeration.None,emojiBlock);
var sendTxt = textView.Text.Trim();
if (!string.IsNullOrEmpty(sendTxt))
{
textView.Text = "";
bases = 0;
Task.Run(() =>
{
//发送输入文本
chat.btn_send_Click(plainString.ToString());
});
}
plainString.SetString (new NSString(""));
return false;
}
return true;
}
private void emojiBlock(NSDictionary dict,NSRange range,ref bool stop)
{
if (dict["NSAttachment"] is EmojiTextAttachment) {
EmojiTextAttachment attachment = (EmojiTextAttachment)dict["NSAttachment"];
plainString.ReplaceCharactersInRange (new NSRange(range.Location + bases,range.Length), attachment.emojiTag);
bases += (int)attachment.emojiTag.Length - 1;
}
}
}
3.EmojiTextAttachment
public class EmojiTextAttachment:NSTextAttachment
{
public NSString emojiTag;
}