简体   繁体   English

如何在Swift中调整视图高度?

[英]How to make the view height resizable in Swift?

I have a custom UIView class where I'm creating a UIView and putting inside UILabel. 我有一个自定义UIView类,可在其中创建UIView并将其放入UILabel。 Initially, I set UIView height equal to 60.0. 最初,我将UIView的高度设置为60.0。 But how can I do that my UIView height would resize with UILabel? 但是,如何使用UILabel调整UIView的高度? For example if UILabel contains 5 linesof text UIView height will also increase to 200pt(for example). 例如,如果UILabel包含5行文本,则UIView的高度也会增加到200pt(例如)。

Here is my class: https://gist.github.com/orkhanalizade/747dc4fd1eb9f228ac964fb4048125dc 这是我的课: https : //gist.github.com/orkhanalizade/747dc4fd1eb9f228ac964fb4048125dc

I have tried 我努力了

self.translatesAutoresizingMaskIntoConstraints = false
self.heightAnchor.constraint(greaterThanOrEqualToConstant: 60.0).isActive = true
NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 60.0).isActive = true

but it did not help me What I do wrong and how can I fix it? 但这对我没有帮助,我该怎么办,如何解决?

Since you are resizing the constants, you may want to use layoutIfNeeded() . 由于您正在调整常量的大小,因此您可能要使用layoutIfNeeded() It will force update the constraints in the view. 它将强制更新视图中的约束。 You can read more about it in Apple's documentation . 您可以在Apple 文档中阅读有关它的更多信息。

只需根据文本计算高度,并使用UIView.animate()方法更新UIView的高度约束即可。

Couple notes... 情侣笔记...

1) In general, a view should not set its own frame. 1)通常,视图不应设置自己的框架。 What happens if you want to add MyView as a subview of another view? 如果要将MyView添加为另一个视图的子视图会怎样? Setting its frame as you have: 根据需要设置其框架:

width: UIScreen.main.bounds.width - 16.0

will not give you the desired results. 不会给您想要的结果。

2) You do not need: 2)你并不需要:

self.addConstraints(constraints)

3) I find it helpful to give elements different, obvious background colors -- makes it easy to see what the frames are doing. 3)我发现为元素赋予不同的明显背景色很有帮助-轻松查看框架的功能。

Here is an edited version of your gist, along with a view controller to add / display it: 这是要点的编辑版本,以及添加/显示它的视图控制器:

import UIKit

class MyView: UIView {
    var label: UILabel!

    var text: String? {
        didSet {
            label.text = text
        }
    }

    var cornerRadius: CGFloat = 0.0 {
        didSet {
            self.layer.cornerRadius = self.cornerRadius
            self.layer.masksToBounds = true
        }
    }

    var textColor: UIColor = UIColor.black {
        didSet {
            label.textColor = textColor
        }
    }

    var isTextCentered: Bool = false {
        didSet {
            self.label.textAlignment = isTextCentered ? .center : .left
        }
    }

    init() {
        // we'll be using constraints, so no need to set a frame
        super.init(frame: CGRect.zero)
        initialize()
    }

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

    fileprivate func initialize() {

        label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.numberOfLines = 0

        self.addSubview(label)

        let constraints = [
            NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 8.0),
            NSLayoutConstraint(item: label, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 8.0),
            NSLayoutConstraint(item: label, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: -8.0),
            NSLayoutConstraint(item: label, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: -8.0)
        ]
        NSLayoutConstraint.activate(constraints)

        // so we can see self's frame
        self.backgroundColor = .red

        // so we can see label's frame
        label.backgroundColor = .yellow

    }
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // instantiate the custom view
        let v = MyView()

        // we'll be using constraints
        v.translatesAutoresizingMaskIntoConstraints = false

        // add the view
        view.addSubview(v)

        NSLayoutConstraint.activate([
            // constrain Top: 60 / Leading: 8 / Trailing: -8
            v.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 60.0),
            v.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 8.0),
            v.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -8.0),

            // constrain height >= 60
            v.heightAnchor.constraint(greaterThanOrEqualToConstant: 60.0),
            ])

        // add 10 lines of text
        v.text = (1...10).map({ "Line \($0)" }).joined(separator: "\n")

    }

}

And the result: 结果:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM