2016-08-05 14 views
0

NSAttributedStringの境界矩形を計算し、その属性付き文字列をUITextViewに入れようとしています。私はテキストの上にUITextViewのサイズを設定したいと思います。私が手動で計算したい理由は、このUITextViewUITableViewCellにあり、セルの高さに自動次元を使用したくないからです。NSAttributedString文字ラップを使用したワードラップを使用したGetBoundingRect

string myString = "This is some test string that should be long enough to be word wrapped"; 

var boldAttributes = new UIStringAttributes(); 
boldAttributes.ForegroundColor = UIColor.Black; 
boldAttributes.Font = AppDelegate.SegoeUIBold.WithSize (14); 

var attributedString = new NSMutableAttributedString (myString, boldAttributes); 

var rect = attributedString.GetBoundingRect(new CGSize(UIScreen.MainScreen.Bounds.Width - 16, 10000), NSStringDrawingOptions.UsesFontLeading|NSStringDrawingOptions.UsesLineFragmentOrigin, null); 
var height = Math.Ceiling(rect.Height); 

これはほとんどの場合動作します。しかし、それが失敗する特殊なケースがいくつかあります。この場合、私は3行に分割される文字列を持っています。

この


単語
包まれたように十分に長くなければならないいくつかのテスト文字列です。

したがって、GetBoundingRectは、3行分の高さを返す必要があります。しかし、2行分の高さしか返しません。私が見つけたのは、文字をラップしてUITextViewsをラップするとすべてがうまくいくようです。だから私の文字列は、最後に次のようになります。

これは言葉 ラップするのに十分な長
EからBすべきいくつかのテスト文字列です。

attributedString.GetBoundingRect()に文字の折り返しの代わりに語の折り返しを行う方法がわかりません。何か案は?

答えて

-1

は、このいずれかを使用してください:

public override void ViewDidLoad() 
    { 
     nfloat padding = 70; 
     nfloat tfWidth = UIScreen.MainScreen.Bounds.Width - 2 * padding; 

     string myString = "This is some test string that should be long enough to be word wrapped"; 

     UILabel tf = new UILabel (new CGRect (padding,100,tfWidth,0)); 
     tf.Text = myString; 
     tf.BackgroundColor = UIColor.Red; 
     tf.Lines = int.MaxValue; 
     tf.LineBreakMode = UILineBreakMode.WordWrap; 
     tf.Font = UIFont.SystemFontOfSize(14); 
     this.View.AddSubview (tf); 

     NSString nsStr = new NSString(myString); 
     nfloat height = nsStr.GetBoundingRect (
      new CoreGraphics.CGSize (tfWidth,float.MaxValue), 
      NSStringDrawingOptions.UsesLineFragmentOrigin | NSStringDrawingOptions.UsesFontLeading, 
      new UIStringAttributes(){Font = tf.Font}, 
      null).Size.Height; 
     tf.Frame = new CGRect (tf.Frame.Location, new CGSize (tfWidth, height)); 
    } 

そしてUITableViewSourceに、私はこのコードを使用します。

public override nfloat GetHeightForRow (UITableView tableView, Foundation.NSIndexPath indexPath) 
    { 
     CellItem item = dataList [indexPath.Row]; 
     NSString nsStr = new NSString(item.Message); 
     nfloat textWidth = item.CellWidth; 
     nfloat height = nsStr.GetBoundingRect (
      new CoreGraphics.CGSize (textWidth,float.MaxValue), 
      NSStringDrawingOptions.UsesLineFragmentOrigin | NSStringDrawingOptions.UsesFontLeading, 
      new UIStringAttributes(){Font = item.Font}, 
      null).Size.Height; 
      return height; 
    } 

したい場合は、各セルごとに異なるフォントを使用することができます。

お手数ですがお手伝いします。

関連する問題