在关闭自动布局的情况下更改UIView的高度

时间:2015-04-27 15:34:42

标签: ios swift uiview resize

关闭视图的自动布局。然而,这不起作用。我对身高没有任何限制。只有等于父视图宽度的宽度。

@IBOutlet weak var questionTextView: UITextView!
override func viewDidLoad() {
  var newFrame = CGRectMake(0, 0, 300, 202)
  questionView.frame = newFrame
}

4 个答案:

答案 0 :(得分:29)

您是否在界面构建器中为整个笔尖关闭了自动布局?

您无法在界面构建器中关闭特定子视图的自动布局 - 您只能在运行时以编程方式执行此操作。

根据你的说法,你仍然有一个约束活跃。当你关闭自动布局时,你有什么限制?

如果您启用了自动布局,则使用框架设置视图的高度将不起作用,因为它会与自动布局规则冲突。

如果您需要更改自动布局处于活动状态的视图的高度,则需要为高度约束创建IBOutlet并在运行时修改它,即:

@IBOutlet weak var heightConstraint: NSLayoutConstraint!

self.heightConstraint.constant = 200

答案 1 :(得分:3)

<强> [编辑]

PS。正如公认的答案所说:If you have auto layout active, setting the height for your view by using the frame won't work since it'll conflict with auto layout rules。这种代码的和平会改变框架,因此如果您尝试将此代码用于自动布局,它将无法正常工作。

[原始回答]

您还可以创建UIView扩展程序:

UIViewExtensions.swift

import Foundation
import UIKit

extension UIView {

    // MARK: - Frame

    /**
    Redefines the height of the view

    :param: height The new value for the view's height
    */
    func setHeight(height: CGFloat) {

        var frame: CGRect = self.frame
        frame.size.height = height

        self.frame = frame
    }

    /**
    Redefines the width of the view

    :param: width The new value for the view's width
    */
    func setWidth(width: CGFloat) {

        var frame: CGRect = self.frame
        frame.size.width = width

        self.frame = frame
    }

    /**
    Redefines X position of the view

    :param: x The new x-coordinate of the view's origin point
    */
    func setX(x: CGFloat) {

        var frame: CGRect = self.frame
        frame.origin.x = x

        self.frame = frame
    }

    /**
    Redefines Y position of the view

    :param: y The new y-coordinate of the view's origin point
    */
    func setY(y: CGFloat) {

        var frame: CGRect = self.frame
        frame.origin.y = y

        self.frame = frame
    }
}

我还添加了设置宽度X和Y的方法。您可以在任何想要的视图中使用该扩展名:

yourView.setHeght(100)

答案 2 :(得分:1)

尝试这样的事情:

var someView = UITextView(frame: CGRect(x: 0, y: 0, width: **view.bounds.size.width**, height: 123))
        someView.layer.backgroundColor = UIColor.orangeColor().CGColor
        view.addSubview(someView)

在您的情况下,使用父视图更改视图。

答案 3 :(得分:1)

您只需要实现translatesAutoresizingMaskIntoConstraints,并通过将其设置为true,您可以通过代码编写约束,而无需执行其他操作。

示例:view.translatesAutoresizingMaskIntoConstraints = true

//此代码可以使用

view.frame = CGRect(x: self.playerChatBackground.frame.origin.x, y:                                     
self.playerChatBackground.frame.origin.y, width: 100.0, height: 36.0)
相关问题