简体   繁体   中英

UITextView word-wrap like Android

I have the following 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" />

And a corresponding iOS UITextView (code):

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();

On iOS, it gives me the following result:

在此处输入图像描述

But on Android, the text "Moyennement" that does not fit is correctly truncated:

在此处输入图像描述

What Am I missing here? Thanks in advance.

Try This:

<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" />

I found a solution which is a mix of Andreas Oetjen's suggestion and the use of a UILabel instead of a 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 is no more used as it is conflicting with HyphenationFactor. This would probably work with a UITextView as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM