首页 > 解决方案 > 在 xamarin.ios 中添加新行时如何实现 Multi-line/AutoResizing UITextView,类似于 SMS-app 或 Skype 应用程序

问题描述

我们正在开发 xamarin.ios 中的聊天应用程序,因此我们希望在添加新行时实现自动增长的文本视图,例如 sms 或 Skype 应用程序。如何在 xamarin.ios 中实现这一点。我在这方面做了很多研发并在互联网上进行了很多搜索,但还没有找到任何合适的解决方案。

请指导我解决这个问题。

标签: c#xamarinxamarin.ios

解决方案


参考以下代码:

CGSize oldSize;

public ViewController (IntPtr handle) : base (handle)
{
}

public override void ViewDidLoad ()
{
    base.ViewDidLoad ();
    // Perform any additional setup after loading the view, typically from a nib.

    UITextView textView = new UITextView(new CGRect(20,20,100,30));
    oldSize = textView.Frame.Size;
    textView.Font = UIFont.SystemFontOfSize(16);
    textView.TextColor = UIColor.Black;
    textView.Changed += (sender, e) => {

      if(textView.Text.Length!=0&&textView.Text!="")
        {
            CGRect frame = textView.Frame;

            double newHeight = Math.Ceiling(textView.SizeThatFits(new CGSize(oldSize.Width,9999999999)).Height);

            // update the height if the newHeight larger than the old
            if(newHeight >= oldSize.Height)
             {
                textView.Frame = new CGRect(frame.X, frame.Y, frame.Size.Width, newHeight);
             }
        }   

    };
    View.AddSubview(textView);
}

推荐阅读