当截断的行以\ n

时间:2017-10-26 08:46:19

标签: ios uilabel

UILabel *label
label.numberOfLines = 1;
label.text = @"abc\nabc";
label.lineBreakMode = NSLineBreakByTruncatingTail;

显示为:abc 预期:abc ... 我试图在段落属性中设置属性文本和设置换行模式,但是不起作用-_- //

添加: 如果将'\ n'字符替换为一行文本,则也会显示。如:设置标签宽度为100pt,设置文本'abcabcabcabcabcbacb'和blabla多行,显示为'abcabcabcabca ...'。

因此,如果能够被截断的文本与密钥char'\ n'相关。

3 个答案:

答案 0 :(得分:0)

    let label = UILabel()
    label.frame = CGRect(x: 100, y: 200, width: 50, height: 25)
    label.backgroundColor = UIColor.red
    label.numberOfLines = 0;
    label.lineBreakMode = NSLineBreakMode.byTruncatingTail
    label.text = "abc\nabc"

在1行范围内(例如21)给出行数为0和高度,然后你会得到预期的答案。 如果给出的行数为1,则在第一行中没有任何内容可以截断。只是忽略第二行文本。

答案 1 :(得分:0)

创建一个高度为21的标签(或根据您的意愿)。并设置前,后,顶部和高度约束。使高度约束> =高度。将高度约束连接到类。

 label.numberOfLines = 5;    //set number of lines as you need.
 label.lineBreakMode = NSLineBreakMode.byTruncatingTail  // set as truncate tail to get …
 let strings = "iOS is a mobile operating system created and developed by Apple Inc. exclusively for its hardware. It is the operating system that presently powers many of the company's mobile devices, including the iPhone, iPad, and iPod Touch"
 label.text = strings
 let size: CGSize = label.text!.size(withAttributes [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 14.0)])
 labelHeightConstraint.constant = size.height

答案 2 :(得分:0)

试试这个。

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 50, 200, 25)];
label.lineBreakMode = NSLineBreakByWordWrapping;
label.numberOfLines = 0; //  use 0 for unlimited.
label.preferredMaxLayoutWidth = self.view.frame.size.width;
label.text = @" abc \n abc \n abc \n abc \n abc \n abc \n abc \n abc \n abc \n";
[label sizeToFit];
[label setNeedsDisplay];
[self.view addSubview:label];

请检查讨论。    Adjust UILabel height depending on the text