在容器视图内以编程方式创建的标签不会扩展为文本 [英] Programatically Created Label Within Container View Won't Expand For Text

查看:61
本文介绍了在容器视图内以编程方式创建的标签不会扩展为文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可重用的视图类,将函数 .addDisapearingView()添加到另一个视图时,将在函数参数中显示文本.标签及其容器视图都是以编程方式创建的.当标签中有长文本时,我希望标签和视图的高度都增加.当标签的文本太长时,标签不会增长-随后,文本也不会剪切/转到下一行.我正在尝试使容器视图基于文本以编程方式扩展.

I have a reusable view class, with the function .addDisapearingView() when added to another view displays the text in the functions parameters. Both the label and its container view are programmatically created. When there's long text in the label, I want the label, and the view to both grow in height. When there's text too long for the label, the label doesn't grow-and the text, subsequently, doesn't clip/go to next line. I'm trying to get the container view to expand programmatically based upon the text.

我尝试了一种扩展功能,该功能可以检测标签何时被截断.使用该扩展名,我在标签和视图上使用了 + = 运算符,并且没有运气地将它们都扩展了.

I've tried an extension that detects when the label is truncated. Using that extension, I used the += operator on the label and view to expand both of them with no luck.

while label.isTruncated {
       print("printing while truncating in the while loop")
        regView.frame.size.height += 5
        label.frame.size.height += 5
    }

有趣的是,我之前使用过该代码,并在情节提要中将视图的高度限制加5以扩大文本标签的大小,并且可以正常工作.那使我相信我的问题可能出在编辑 regView 的高度限制的某个地方.

The interesting thing with that is, I've used that code before, with the addition of adding 5 to the height constraint of the view in the storyboard to expand the size of the label for text, and it worked. That lead me to believe that my problem might reside somewhere in editing the height constraint for the regView.

我尝试了

    label.adjustsFontSizeToFitWidth = true
    label.numberOfLines = 3
    label.lineBreakMode = .byWordWrapping
    label.translatesAutoresizingMaskIntoConstraints = false
    label.frame.size.height = regView.frame.size.height
    label.sizeToFit()
    regView.layoutSubviews()

我尝试过更改视图和标签的框架,更改代码顶部的内容以及其他问题的答案.

I've tried changing the frame of the view and label, changing the constaints at the top of the code, and the answers from other questions.

代码:

截断的标签扩展名:

extension UILabel {

var isTruncated: Bool {

    guard let labelText = text else {
        return false
    }

    let labelTextSize = (labelText as NSString).boundingRect(
        with: CGSize(width: frame.size.width, height: .greatestFiniteMagnitude),
        options: .usesLineFragmentOrigin,
        attributes: [.font: font],
        context: nil).size

    return labelTextSize.height > bounds.size.height
}
}

查看约束更改器:

extension UIView {

func updateConstraint(attribute: NSLayoutAttribute, constant: CGFloat) -> Void {
    if let constraint = (self.constraints.filter{$0.firstAttribute == attribute}.first) {
        constraint.constant = constant
        self.layoutIfNeeded()
    }
}
}

整个功能:

func addDisapearingView(toview: UIView, text: String, textColor: UIColor, colorView: UIColor, alpha: CGFloat, height: CGFloat){

    regView.backgroundColor = colorView
    regView.alpha = alpha
    regView.frame = CGRect(x: toview.bounds.minX, y: toview.bounds.minY, width: toview.frame.size.width, height: height)

    toview.addSubview(regView)

    regView.translatesAutoresizingMaskIntoConstraints = false
    if #available(iOS 11.0, *) {
        let guide = toview.safeAreaLayoutGuide
        regView.trailingAnchor.constraint(equalTo: guide.trailingAnchor).isActive = true
        regView.leadingAnchor.constraint(equalTo: guide.leadingAnchor).isActive = true
        regView.topAnchor.constraint(equalTo: guide.topAnchor).isActive = true
        regView.heightAnchor.constraint(equalToConstant: height).isActive = true

    } else {
        NSLayoutConstraint(item: regView,
                           attribute: .top,
                           relatedBy: .equal,
                           toItem: toview, attribute: .top,
                           multiplier: 1.0, constant: 0).isActive = true
        NSLayoutConstraint(item: regView,
                           attribute: .leading,
                           relatedBy: .equal, toItem: toview,
                           attribute: .leading,
                           multiplier: 1.0,
                           constant: 0).isActive = true
        NSLayoutConstraint(item: regView, attribute: .trailing,
                           relatedBy: .equal,
                           toItem: toview,
                           attribute: .trailing,
                           multiplier: 1.0,
                           constant: 0).isActive = true
        NSLayoutConstraint(item: regView, attribute: NSLayoutAttribute.height, relatedBy: .equal, toItem: toview, attribute: .height, multiplier: 1.0, constant: height).isActive = true
        //regView.heightAnchor.constraint(equalToConstant: height).isActive = true
    }

    let label = UILabel(frame: CGRect(x: regView.frame.origin.x, y: regView.frame.origin.y, width: regView.frame.width, height: height))
    label.text = text
    label.font = UIFont(name: "Arial", size: 12)
    label.textColor = textColor
    label.adjustsFontSizeToFitWidth = true
    label.numberOfLines = 3
    label.lineBreakMode = .byWordWrapping
    label.translatesAutoresizingMaskIntoConstraints = false
    label.frame.size.height = regView.frame.size.height
    label.sizeToFit()
    regView.layoutSubviews()
    regView.addSubview(label)
    print("Label Height: \(label.frame.height)")
    print("Reg view height: \(regView.frame.height)")

    while label.isTruncated {
        print("label is truncated")
        regView.frame.size.height += 5
        label.frame.size.height += 5
        label.updateConstraint(attribute: NSLayoutAttribute.height, constant: regView.frame.height)
        label.updateConstraint(attribute: NSLayoutAttribute.width, constant: regView.frame.width)

        regView.layoutSubviews()
        label.sizeToFit()
        print("Label Height: \(label.frame.height)")
        print("Reg view height: \(regView.frame.height)")
    }

    //remove
    Timer.scheduledTimer(withTimeInterval: 2.8, repeats: false) { (action) in
        UIView.animate(withDuration: 2.8, animations: {
            self.regView.removeFromSuperview()
            label.removeFromSuperview()

        })
    }

}

,其调用方式为: ReusableView().addDisapearingView(toview:self.view,text:匿名信息仍会显示在您的个人资料页面中!工作!",textColor:UIColor.white,colorView:UIColor.darkGray,alpha:0.9,高度:20)

有趣的事情(我尝试修复)是,即使高度设置为 40 或一个可以容纳两行文本的值,标签仍然不会展开/截断,如果高度参数为 20 则更是如此.

The interesting thing(That I tried to fix) was that even if the height is set to 40, or a value where two lines of text could fit, the label still doesn't expand/truncate, much less if the height param is 20.

任何帮助将不胜感激!

推荐答案

我想您完全需要自动布局,并使 regView 根据标签的文本展开而没有任何高度限制

I guess you completely need auto-layout and make regView expand according to the label's text without any height constraints

let regView = UIView()

func addDisapearingView(toview: UIView, text: String, textColor: UIColor, colorView: UIColor, alpha: CGFloat, height: CGFloat){

regView.backgroundColor = colorView
regView.alpha = alpha
toview.addSubview(regView)

regView.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 11.0, *) {
    let guide = toview.safeAreaLayoutGuide
    NSLayoutConstraint.activate([
            regView.trailingAnchor.constraint(equalTo: guide.trailingAnchor),
            regView.leadingAnchor.constraint(equalTo: guide.leadingAnchor),
            regView.topAnchor.constraint(equalTo: guide.topAnchor),
           // regView.bottomAnchor.constraint(equalTo: guide.bottomAnchor).isActive = true
           // regView.heightAnchor.constraint(equalToConstant: height).isActive = true
    ])
} else {
    NSLayoutConstraint(item: regView,
                       attribute: .top,
                       relatedBy: .equal,
                       toItem: toview, attribute: .top,
                       multiplier: 1.0, constant: 0).isActive = true
    NSLayoutConstraint(item: regView,
                       attribute: .leading,
                       relatedBy: .equal, toItem: toview,
                       attribute: .leading,
                       multiplier: 1.0,
                       constant: 0).isActive = true
    NSLayoutConstraint(item: regView, attribute: .trailing,
                       relatedBy: .equal,
                       toItem: toview,
                       attribute: .trailing,
                       multiplier: 1.0,
                       constant: 0).isActive = true
   // NSLayoutConstraint(item: regView, attribute: NSLayoutConstraint.Attribute.height, relatedBy: .equal, toItem: toview, attribute: .height, multiplier: 1.0, constant: height).isActive = true
    //regView.heightAnchor.constraint(equalToConstant: height).isActive = true
}

let label = UILabel()
label.text = text
label.font = UIFont(name: "Arial", size: 12)
label.textColor = textColor
label.numberOfLines = 3
label.lineBreakMode = .byWordWrapping
label.translatesAutoresizingMaskIntoConstraints = false
regView.addSubview(label)

    NSLayoutConstraint.activate([
        label.trailingAnchor.constraint(equalTo: regView.trailingAnchor),
        label.leadingAnchor.constraint(equalTo: regView.leadingAnchor),
        label.topAnchor.constraint(equalTo: regView.topAnchor),
        label.bottomAnchor.constraint(equalTo: regView.bottomAnchor) // this is the key behind expanding 

    ])

 Timer.scheduledTimer(withTimeInterval:3, repeats: false) { (action) in
    UIView.animate(withDuration: 2.8, animations: {
        self.regView.removeFromSuperview()
    })
 }

}

let regView = UIView()

func addDisapearingView(toview: UIView, text: String, textColor: UIColor, colorView: UIColor, alpha: CGFloat, height: CGFloat){

    regView.backgroundColor = colorView
    regView.alpha = alpha
    toview.addSubview(regView)

    regView.translatesAutoresizingMaskIntoConstraints = false
    var topCon:NSLayoutConstraint!

    if #available(iOS 11.0, *) {
        let guide = toview.safeAreaLayoutGuide
        topCon = regView.bottomAnchor.constraint(equalTo: guide.topAnchor)
        topCon.isActive = true
        NSLayoutConstraint.activate([
            regView.trailingAnchor.constraint(equalTo: guide.trailingAnchor),
            regView.leadingAnchor.constraint(equalTo: guide.leadingAnchor),
            // regView.bottomAnchor.constraint(equalTo: guide.bottomAnchor).isActive = true
            // regView.heightAnchor.constraint(equalToConstant: height).isActive = true
            ])
    } else {
        topCon =  NSLayoutConstraint(item: regView,
                           attribute: .bottom,
                           relatedBy: .equal,
                           toItem: toview, attribute: .top,
                           multiplier: 1.0, constant: 0)
            topCon.isActive = true
        NSLayoutConstraint(item: regView,
                           attribute: .leading,
                           relatedBy: .equal, toItem: toview,
                           attribute: .leading,
                           multiplier: 1.0,
                           constant: 0).isActive = true
        NSLayoutConstraint(item: regView, attribute: .trailing,
                           relatedBy: .equal,
                           toItem: toview,
                           attribute: .trailing,
                           multiplier: 1.0,
                           constant: 0).isActive = true
        // NSLayoutConstraint(item: regView, attribute: NSLayoutConstraint.Attribute.height, relatedBy: .equal, toItem: toview, attribute: .height, multiplier: 1.0, constant: height).isActive = true
        //regView.heightAnchor.constraint(equalToConstant: height).isActive = true
    }

    let label = UILabel()
    label.text = text
    label.font = UIFont(name: "Arial", size: 12)
    label.textColor = textColor
    label.numberOfLines = 3
    label.lineBreakMode = .byWordWrapping
    label.translatesAutoresizingMaskIntoConstraints = false
    regView.addSubview(label)

    NSLayoutConstraint.activate([
        label.trailingAnchor.constraint(equalTo: regView.trailingAnchor),
        label.leadingAnchor.constraint(equalTo: regView.leadingAnchor),
        label.topAnchor.constraint(equalTo: regView.topAnchor),
        label.bottomAnchor.constraint(equalTo: regView.bottomAnchor) // this is the key behind expanding

        ])


     regView.layoutIfNeeded()

    topCon.constant += self.regView.frame.height

    UIView.animate(withDuration: 2) {
        toview.layoutIfNeeded()
    }


    Timer.scheduledTimer(withTimeInterval:3, repeats: false) { (action) in
        UIView.animate(withDuration: 2.8, animations: {
            self.regView.removeFromSuperview()
        })
    }

}

这篇关于在容器视图内以编程方式创建的标签不会扩展为文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆