ios - 以编程方式根据行数动态调整 UILabel 的大小

标签 ios swift autolayout uilabel

我有一个 View,我在其中创建了一个 UILabel,其 numberOfLines 等于零。我希望根据我的标签内容调整标签大小(根据 numberOfLines)。但是,我尝试了很多东西,包括所有 this ,它仍然对我不起作用。我用 Neon AutoLayot 库。

这是我查看的全部内容:

import UIKit
import Neon

class AdditionalDescriptionView: UIView {

    lazy var locationLabel = UILabel()
    lazy var seasonLabel = UILabel()
    lazy var quantityLabel = UILabel()
    lazy var durationLabel = UILabel()
    lazy var requirementsLabel = UILabel()
    var height: CGFloat = 0
    var text = NSString()
    var size = CGSize()

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setup() {
        locationLabel.textAlignment = .left
        locationLabel.text = "Локация: Каркаралинск (200км от Караганды)"
        locationLabel.textColor = .black
        locationLabel.font = UIFont.avenirNextRegular(ofSize: 14)
        locationLabel.numberOfLines = 0
        seasonLabel.textAlignment = .left
        seasonLabel.textColor = .black
        seasonLabel.font = UIFont.avenirNextRegular(ofSize: 14)
        seasonLabel.text = "Сезоны: все"
        quantityLabel.textAlignment = .left
        quantityLabel.textColor = .black
        quantityLabel.text = "Количество людей: 5-25"
        quantityLabel.font = UIFont.avenirNextRegular(ofSize: 14)
        durationLabel.textAlignment = .left
        durationLabel.textColor = .black
        durationLabel.text = "Длительность тура: 3 суток"
        durationLabel.font = UIFont.avenirNextRegular(ofSize: 14)
        requirementsLabel.textAlignment = .left
        requirementsLabel.textColor = .black
        requirementsLabel.text = "Требования: удобная обувь, дополнительный груз не более 3кг, минимум 1л питьевой воды. Лицам с кардио- и дыхательными проблемами не рекомендуется участие в туре."
        requirementsLabel.font = UIFont.avenirNextRegular(ofSize: 14)
        requirementsLabel.numberOfLines = 0
        requirementsLabel.lineBreakMode = .byWordWrapping
        requirementsLabel.sizeToFit()

        self.addSubview(locationLabel)
        self.addSubview(seasonLabel)
        self.addSubview(quantityLabel)
        self.addSubview(durationLabel)
        self.addSubview(requirementsLabel)

        updateConstraints()
    }

    override func updateConstraints() {
        locationLabel.anchorToEdge(.top, padding: 0, width: self.frame.width, height: AutoHeight)
        seasonLabel.align(.underCentered, relativeTo: locationLabel, padding: 0, width: self.frame.width, height: AutoHeight)
        seasonLabel.alignAndFillWidth(align: .underCentered, relativeTo: locationLabel, padding: 0, height: AutoHeight)
        quantityLabel.alignAndFillWidth(align: .underCentered, relativeTo: seasonLabel, padding: 0, height: AutoHeight)
        durationLabel.alignAndFillWidth(align: .underCentered, relativeTo: quantityLabel, padding: 0, height: AutoHeight)
        // fix requirementsLabel height
        requirementsLabel.alignAndFillWidth(align: .underCentered, relativeTo: durationLabel, padding: 0, height: AutoHeight)
        height = locationLabel.frame.height+seasonLabel.frame.height+quantityLabel.frame.height+durationLabel.frame.height+requirementsLabel.frame.height
    }
}

使用它来实际添加 View :

self.view.addSubview(additional)
additional.anchorAndFillEdge(.top, xPad: 0, yPad: 0, otherSize: additional.height)
additional.updateConstraints()

最佳答案

我放弃了使用 Neon 解决这个问题的尝试。问题本质上是您试图为您的容器 View 定义一个具体的高度,同时试图将其中的元素彼此锚定及其边距。我最终只使用了使用布局 anchor 的标准自动布局 API。然后,您需要做的就是指定容器的宽度,它的高度将根据其包含的标签的大小自动设置。解决方法如下:

import UIKit

class AdditionalDescriptionView: UIView {

    lazy var locationLabel = UILabel()
    lazy var seasonLabel = UILabel()
    lazy var quantityLabel = UILabel()
    lazy var durationLabel = UILabel()
    lazy var requirementsLabel = UILabel()
    var text = NSString()
    var size = CGSize()

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setup() {
        self.translatesAutoresizingMaskIntoConstraints = false
        backgroundColor = UIColor.blue
        locationLabel.textAlignment = .left
        locationLabel.text = "Локация: Каркаралинск (200км от Караганды)"
        locationLabel.textColor = .black
        locationLabel.font = UIFont.avenirNextRegular(ofSize: 14)
        locationLabel.numberOfLines = 0
        seasonLabel.textAlignment = .left
        seasonLabel.textColor = .black
        seasonLabel.font = UIFont.avenirNextRegular(ofSize: 14)
        seasonLabel.text = "Сезоны: все"
        quantityLabel.textAlignment = .left
        quantityLabel.textColor = .black
        quantityLabel.text = "Количество людей: 5-25"
        quantityLabel.font = UIFont.avenirNextRegular(ofSize: 14)
        durationLabel.textAlignment = .left
        durationLabel.textColor = .black
        durationLabel.text = "Длительность тура: 3 суток"
        durationLabel.font = UIFont.avenirNextRegular(ofSize: 14)
        requirementsLabel.textAlignment = .left
        requirementsLabel.textColor = .black
        requirementsLabel.text = "Требования: удобная обувь, дополнительный груз не более 3кг, минимум 1л питьевой воды. Лицам с кардио- и дыхательными проблемами не рекомендуется участие в туре."
        requirementsLabel.font = UIFont.avenirNextRegular(ofSize: 14)
        requirementsLabel.numberOfLines = 0
        requirementsLabel.lineBreakMode = .byWordWrapping

        self.addSubview(locationLabel)
        locationLabel.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(seasonLabel)
        seasonLabel.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(quantityLabel)
        quantityLabel.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(durationLabel)
        durationLabel.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(requirementsLabel)
        requirementsLabel.translatesAutoresizingMaskIntoConstraints = false

        locationLabel.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        seasonLabel.topAnchor.constraint(equalTo: locationLabel.bottomAnchor).isActive = true
        quantityLabel.topAnchor.constraint(equalTo: seasonLabel.bottomAnchor).isActive = true
        durationLabel.topAnchor.constraint(equalTo: quantityLabel.bottomAnchor).isActive = true
        requirementsLabel.topAnchor.constraint(equalTo: durationLabel.bottomAnchor).isActive = true
        requirementsLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true

        locationLabel.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
        seasonLabel.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
        quantityLabel.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
        durationLabel.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
        requirementsLabel.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true

        locationLabel.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
        seasonLabel.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
        quantityLabel.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
        durationLabel.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
        requirementsLabel.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
    }
}


class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let additional = AdditionalDescriptionView()
        self.view.addSubview(additional)
        additional.widthAnchor.constraint(equalTo: self.view.widthAnchor).isActive = true
        additional.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
    }
}

关于ios - 以编程方式根据行数动态调整 UILabel 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42320056/

相关文章:

ios - 自定义单元格中的按钮操作

swift - fatal error : Not enough bits to represent the passed value

ios - 约束不重新调整堆栈 View 的大小

ios - 自动布局黄色警告。它会使我的应用程序在运行时崩溃吗

ios - MFMailcomposeviewcontroller 发送按钮被禁用

ios - 异步 NSURLConnection 在每个字节之间接收空字节

ios - 对泛型类型 'Set' 的引用需要 <...> 中的参数 & 无法推断泛型参数 'element'

ios - iOS坐标系在设备之间是否相等?

ios - Rx swift : Return a new observable with an error

ios - GCDWebServer静态网站问题