ios 如何使用 Swift 以编程方式增加 UIView 的高度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43010173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:00:50  来源:igfitidea点击:

How to programmatically increase the height of UIView with Swift

iosswiftxcodeuiviewconstraints

提问by Lance Samaria

Inside IB I have a viewController with a segmentedControl and 2 containerViews. In each containerView I have a tableView. From each tableView I push on a detailView. My auto layout is in IB.

在 IB 中,我有一个带有 segmentedControl 和 2 个 containerViews 的 viewController。在每个 containerView 中,我都有一个 tableView。从每个 tableView 我推一个 detailView。我的自动布局在 IB 中。

Once I pick a segment, I see the corresponding tableView, I pick a cell and the correct detailView gets pushed on the scene.

一旦我选择了一个段,我就会看到相应的 tableView,我选择了一个单元格,然后正确的 detailView 就会被推送到场景中。

The issue is once the detailView gets pushed on the segmentedControl is still visible. I decided to hide the segmentedControl which works but there is a big empty space there. I tried to programmatically increase the size of detailView's view but it's not expanding. From what I read it's because I made the initial constraints in storyboards.

问题是一旦将 detailView 推送到 segmentedControl 上仍然可见。我决定隐藏有效的 segmentedControl 但那里有一个很大的空白空间。我试图以编程方式增加 detailView 视图的大小,但它没有扩展。从我读到的内容来看,这是因为我在故事板中设置了初始约束。

How to I programmatically get the detailView's view to expand?

如何以编程方式让 detailView 的视图展开?

code:

代码:

DetailViewController: UIViewController{

override func viewDidLoad() {
        super.viewDidLoad()

 //this isn't increasing the view's size
 self.view.frame.size.height += 20.0

 //doesn't work. I get an error on the last argument
 self.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height += 20.0)

 //doesn't work. I get an error on the last argument
 self.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.size.height += 20.0)
 }

}

Errors:

错误:

//Error for the last argument- height: *self.view.frame.height += 20.0*
self.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height += 20.0)

Left side of mutating operator isn't mutable: 'height' is a get-only property

变异运算符的左侧是不可变的:'height' 是一个 get-only 属性

//Error for the last argument- *self.view.frame.size.height += 20.0*:
self.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.size.height += 20.0)

Cannot invoke initializer for type 'CGRect' with an argument list of type '(x: Int, y: Int, width: CGFloat, height: ())'

无法使用类型为 '(x: Int, y: Int, width: CGFloat, height: ())' 的参数列表调用类型为 'CGRect' 的初始化程序

回答by CoolPenguin

You need to create an outlet for the height constraint of the detail view, and then you can adjust the height programmatically like this myHeightConstraint.constant += extraHeightwhere extraHeightis a number indicating how much taller you want the detail view to be. You also may need to call self.view.layoutIfNeeded()afterwards.

您需要为详细视图的高度约束创建一个出口,然后您可以像这样以编程方式调整高度myHeightConstraint.constant += extraHeight,其中extraHeight是一个数字,指示您希望详细视图多高。您可能还需要self.view.layoutIfNeeded()事后致电。

To create an outlet from a constraint, control drag from the constraint in the storyboard editor (just like you would for an outlet of a UIView) into your code.

要从约束创建出口,请控制从故事板编辑器中的约束拖动(就像 UIView 的出口一样)到您的代码中。

You are right - because you are using auto layout and constraints, the adjustments need to be made with constraints too. Setting the raw frames can lead to unexpected behavior. Let me know if you have any other questions or difficulties.

您是对的 - 因为您使用的是自动布局和约束,所以也需要使用约束进行调整。设置原始帧可能会导致意外行为。如果您有任何其他问题或困难,请告诉我。

回答by rmaddy

Inside the CGRectinitializer you should not be using +=, just +.

CGRect初始化程序中,您不应该使用+=,只是+.

Change:

改变:

self.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height += 20.0)

to:

到:

self.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height + 20.0)

You should not be trying to change the value of self.view.frame.heightinside the initializer.

您不应该尝试更改self.view.frame.height初始值设定项中的值。

回答by moraei

Swift 4.2

斯威夫特 4.2

I create an example for you programmatically:

我以编程方式为您创建一个示例:

    var flowHeightConstraint: NSLayoutConstraint?

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        view.addSubview(button)
        button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        button.widthAnchor.constraint(equalToConstant: 100).isActive = true
        flowHeightConstraint = button.heightAnchor.constraint(equalToConstant: 30)
        flowHeightConstraint?.isActive = true
    }

    @objc func animateButtonTapped() {
        UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: .curveEaseOut, animations: {
            self.flowHeightConstraint?.constant = 100
            self.view.layoutIfNeeded()
        }, completion: nil)
    }

    lazy var button: UIButton = {
       let button = UIButton()
        button.translatesAutoresizingMaskIntoConstraints = false
        button.backgroundColor = .green
        button.addTarget(self, action: #selector(animateButtonTapped), for: .touchUpInside)
        return button
    }()

this line of code create a button an on tapped change height of button with animation.

这行代码创建了一个按钮,并通过动画更改按钮的高度。

hope this help :)

希望这有帮助:)

回答by biomiker

For me, a programmatic solution wouldn't require me to create an outlet for every height constraint I might want to modify. Here's a code-only solution that works nicely for me. It should work whether the original constraint was created on the storyboard or programmatically. It also provides an option to animate the change if desired -- although I'm not sure if this would work if the view is nested in a complex hierarchy.

对我来说,程序化解决方案不需要我为我可能想要修改的每个高度约束创建一个出口。这是一个仅适用于我的代码解决方案。无论原始约束是在情节提要上创建还是以编程方式创建,它都应该起作用。如果需要,它还提供了一个为更改设置动画的选项——尽管我不确定如果视图嵌套在复杂的层次结构中这是否可行。

extension UIView {
    func setHeight(_ h:CGFloat, animateTime:TimeInterval?=nil) {

        if let c = self.constraints.first(where: { ##代码##.firstAttribute == .height && ##代码##.relation == .equal }) {
            c.constant = CGFloat(h)

            if let animateTime = animateTime {
                UIView.animate(withDuration: animateTime, animations:{
                    self.superview?.layoutIfNeeded()
                })
            }
            else {
                self.superview?.layoutIfNeeded()
            }
        }
    }
}

回答by Joe

Is there any height constraints set for segmentedControl, if so you might want to remove them while loading the detail view

是否为 segmentedControl 设置了任何高度约束,如果是这样,您可能希望在加载详细信息视图时删除它们

回答by Nupur Sharma

Use self.view.frame.size.height = 80

使用 self.view.frame.size.height = 80