【问题标题】:Swift constraint autosize label widthSwift 约束自动调整标签宽度
【发布时间】:2017-06-24 11:28:01
【问题描述】:

这是我让 UILabel 自动调整大小的代码:

        gmatesLabel.topAnchor.constraint(equalTo: homeButton.bottomAnchor, constant: 5).isActive = true
        gmatesLabel.trailingAnchor.constraint(equalTo: gmatesUniversitySeparatorView.leadingAnchor, constant: -20).isActive = true
        gmatesLabel.heightAnchor.constraint(equalToConstant: 40).isActive = true
//        gmatesLabel.widthAnchor.constraint(equalTo: gmatesLabel.widthAnchor, multiplier: 0.5)
        gmatesLabel.setContentCompressionResistancePriority(UILayoutPriorityRequired, for: .horizontal) 

我也试过这段代码:

gmatesLabel.widthAnchor.constraint(equalTo: gmatesLabel.widthAnchor, multiplier: 0.5, constant: 150).isActive = true

但是标签总是缩小的问题,我在这里错过了什么?

更新 我已经添加了leadingAnchor

gmatesLabel.heightAnchor.constraint(equalToConstant: 40).isActive = true

这是设置我的标签的功能:

fileprivate func setCommonGmatesText(_ count: Int ) {

    let commonGmatesString   =  NSMutableAttributedString(string: "\(count)", attributes: [NSFontAttributeName : Font.boldFont22, NSForegroundColorAttributeName: Color.lightGray])
    commonGmatesString.append(NSAttributedString(string: "\(NSLocalizedString("commonGmates", comment: "How much common gmates we got"))", attributes: [NSFontAttributeName : Font.regularFont14, NSForegroundColorAttributeName: Color.lightGray]))
    gmatesLabel.attributedText = commonGmatesString
    gmatesLabel.sizeToFit()
}

【问题讨论】:

  • 为什么没有主播?例如,您可以定义一个领先的锚点并定义为大于 5。如果需要,标签将增长到该大小,如果不是(因为文本不够长),它将仅适合文本
  • @Ocunidee 我没有添加leadingAnchor,因为我的视图将被锁定top-right 并且定义height-width 就足够了,无需添加其他约束。以这种方式使用故事板工作正常,但以编程方式我不知道为什么它不起作用!
  • 这里你想调整宽度,所以你不能设置宽度,只能设置高度。为了确保您的标签不会大于它的超级视图,您应该设置一个等于或大于 8pt(通常的边距大小)的前导锚。您的标签将调整大小。也许截图可以帮助您了解您的确切问题
  • @Ocunidee 我添加了领先的锚,但总是得到相同的结果检查我的更新
  • 我可以想到几件事:您在标签中的何处添加文本?您应该在向其添加文本后执行 yourLabel.sizeToFit() 并且还应该定义 lineBreakMode:yourLabel.lineBreakMode = .byWordWrapping

标签: ios swift cocoa-touch autolayout constraints


【解决方案1】:

您应该为您的标签设置一个leadingAnchor(例如大于或等于8pt),这样标签就不会变得比它的超级视图更大。

你还应该设置 lineBreakMode:

yourLabel.lineBreakMode = .byWordWrapping

【讨论】:

    猜你喜欢
    • 2014-12-17
    • 2013-11-19
    • 1970-01-01
    • 1970-01-01
    • 2013-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-21
    相关资源
    最近更新 更多