UILabel文本被截断

5

我正在尝试创建一个类似于Youtube的应用程序。在这个项目中,我没有使用IB。我遇到的问题是当一句话太长无法放在一行时,文本会被截断。我想要像原始的Youtube应用程序那样显示第一句话而不被切断。UILabel的代码如下。

let titleLabel:UILabel = {
        let label = UILabel()
        label.text = "Linkin Park - Numb"
        label.translatesAutoresizingMaskIntoConstraints = false
        label.numberOfLines = 2
        return label
    }()

//标题标签的限制
    //top
addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .Top,       relatedBy: .Equal, toItem: thumbnailImageView, attribute: .Bottom, multiplier: 1, constant: 8))

    //left
  addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .Left, relatedBy: .Equal, toItem: profileImageView, attribute: .Right, multiplier: 1, constant: 8))
    //right
addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .Right, relatedBy: .Equal, toItem: thumbnailImageView, attribute: .Right, multiplier: 1, constant: 0))
    // height
titleLabelHeightConstraint = NSLayoutConstraint(item: titleLabel, attribute: .Height, relatedBy: .Equal, toItem: self, attribute: .Height, multiplier: 0, constant: 44)
        addConstraint(titleLabelHeightConstraint!)

以下图像可以让您了解我上面所说的内容。 我的应用 我也发布了原始Youtube应用程序的图像。在原始的Youtube应用程序中,第一句话从未被截断。 Youtube 应用 有没有办法在我的应用程序中像Youtube那样显示文本?

1
尝试移除高度约束,它会自动扩展高度。 - xmhafiz
谢谢,这个已经可以了。 - Mamun Simul
有一个小问题。当我删除高度约束时,第二行与第一行不对齐,它稍微向右移动了一点。你知道如何解决吗? - Mamun Simul
取决于您如何为第二个标签添加约束条件。它应该与上一个标签有顶部间距。 - xmhafiz
4个回答

1
你把标签的高度约束固定了,需要移除它以实现动态高度。

1
尝试做这个:-
label.lineBreakMode = .ByCharWrapping
label.numberOfLines = 0

我尝试了你的方法,但并没有完整地显示整个句子,虽然第一行没有被截断。 - Mamun Simul

1
Hi just remove the height constraint 
titleLabelHeightConstraint = NSLayoutConstraint(item: titleLabel, attribute: .Height, relatedBy: .Equal, toItem: self, attribute: .Height, multiplier: 0, constant: 44)
        addConstraint(titleLabelHeightConstraint!)

and **add the bottom constraint to the label** as in current scenario the label does't have the bottom constraint so that label does't know how much increase .

我尝试了你的代码,但如果我添加底部约束,情况会变得更糟,因为在TitleLabel底部还有另一个标签,该标签具有顶部约束,所以我不需要为TitleLabel添加底部约束。 - Mamun Simul

-1

如果你在使用Xcode,你可以从main.storyboard手动增加你的标签宽度


1
原帖提到未使用IB(也就是没有故事板)。 - HangarRash

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接