像Android一样的UITextView自动换行

问题描述

我有以下Android TextView:

<TextView
    fontPath="fonts/Ubuntu-Light.ttf"
    android:layout_width="50sp"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="Moyennement"
    android:id="@+id/txt_score2"
    android:gravity="center"
    android:textSize="8sp"
    android:textColor="@color/indicator_score_text" />

以及相应的iOS UITextView(代码):

var smiley = new UITextView { Text = name,ScrollEnabled = false,Font = FontHelpers.GenerateUIFont("Ubuntu-Light",8),};
smiley.TextContainer.MaximumNumberOfLines = 2;
smiley.TextContainer.LineBreakMode = UILineBreakMode.CharacterWrap;
smiley.SizetoFit();

在iOS上,它给我以下结果:

enter image description here

但是在Android上,不正确的文本“ Moyennement”已被正确截断:

enter image description here

在这里想念什么? 预先感谢。

解决方法

尝试:

<TextView
    fontPath="fonts/Ubuntu-Light.ttf"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="Moyenne-\nment"
    android:id="@+id/txt_score2"
    android:gravity="center"
    android:textSize="8sp"
    android:textColor="@color/indicator_score_text" />
,

我找到了一个解决方案,其中包括Andreas Oetjen的建议以及使用UILabel而不是UITextView的组合。

NSMutableParagraphStyle paragraphStyle = new NSMutableParagraphStyle();
paragraphStyle.HyphenationFactor = 1.0f;
var hyphenAttribute = new UIStringAttributes();
hyphenAttribute.ParagraphStyle = paragraphStyle;
var attributedString = new NSAttributedString(str: name,attributes: hyphenAttribute);
var smiley = new UILabel { AttributedText = attributedString,Font = FontHelpers.GenerateUIFont("Ubuntu-Light",10),TranslatesAutoresizingMaskIntoConstraints = false };
smiley.Lines = 2;
smiley.TextAlignment = UITextAlignment.Center;

LineBreakMode不再使用,因为它与HyphenationFactor冲突。这可能也可以与UITextView一起使用。