【问题标题】:Resize UILabel & UIView automatically on UIViewController in a Playground在 Playground 中的 UIViewController 上自动调整 UILabel 和 UIView 的大小
【发布时间】:2017-04-01 11:31:28
【问题描述】:

我的 Playground Book 中有一个 UIViewController,我想在上面放置一个 UILabelUIView

在 Playground Book 中,用户可以通过手势调整UIViewController 的大小,但内容(UILabelUIView无法调整大小。这意味着UILabelUIView 有时比实际的UIViewController 大。 UILabelUIView 有时也需要关闭。

我像这样创建了我的UIViewController

let window1 = WMWindow(frame: CGRectMake(150,150,400,300))
window1.title = "View 2"

let vc1 = UIViewController()
vc1.title = "View 2"
vc1.view = UIView()
vc1.view.backgroundColor = UIColor.white
let nc1 = UINavigationController(rootViewController: vc1)

window1.rootViewController = nc1
window1.makeKeyAndVisible()

window.addSubview(window1)

和我的UILabel & UIView 这样

let textLabel = UILabel(frame: CGRect(x: 30, y: window1.bounds.height-50, width: window1.bounds.width, height: window1.bounds.height))
textLabel.lineBreakMode = .byWordWrapping
textLabel.numberOfLines = 5
textLabel.textColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)

let backgroundView = UIView(frame: CGRect(x: 0, y: window1.bounds.height, width: window1.bounds.width, height: 200))
backgroundView.backgroundColor = #colorLiteral(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)
backgroundView.alpha = 0.7

当然,我将它们作为子视图添加到 UIViewController

现在如何更改 UILabelUIView 以根据 UIViewController 的大小自动调整大小?

我发现我可以使用vc1.view.addSubview(...) 代替window1.addSubview(...)。此行使用户能够正确调整视图和子视图的大小,但不幸的是,几秒钟后,子视图将位于与开头相同的位置。

【问题讨论】:

    标签: ios swift cocoa-touch uiviewcontroller


    【解决方案1】:

    您需要为视图添加约束,这会自动发生。

    例如:

    backgroundView.leadingAnchor.constraint(equalTo: vc1.view.leadingAnchor).isActive = true;
    backgroundView.topAnchor.constraint(equalTo: vc1.view.topAnchor).isActive = true;
    backgroundView.trailingAnchor.constraint(equalTo: vc1.view.trailingAnchor).isActive = true;
    backgroundView.bottomAnchor.constraint(equalTo: vc1.view.bottomAnchor).isActive = true;
    

    将固定您的 backgroundView 以匹配视图控制器的确切大小。

    与往常一样,文档中还有更多内容:
    Understanding AutoLayout
    Programatically creating constraints
    NSLayoutAnchor reference

    --
    更新:
    我更仔细地查看了您的代码,并且您的评论似乎您将视图添加为窗口的子视图。你一般不应该那样做。你应该这样做:vc1.view.addSubview(...)。也不需要这个vc1.view = UIView(),除非你想在那里提供一个自定义的UIView 子类。

    【讨论】:

    • 这在操场上不起作用,因为我不能使用self。你有别的想法吗?
    • 哦!对不起!您需要将 self 替换为存储视图控制器的变量:) 您是如何将视图添加为子视图的?
    • 赞这个window1.addSubview(backgroundView)
    • 如果我移动 UIViewController 它总是在几秒钟后移动到相同的位置。
    • 收到vc.view.addSubview(...) 的错误:Value of type 'UIViewController' has no member 'addSubview'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-05
    • 1970-01-01
    • 2013-07-16
    相关资源
    最近更新 更多