【问题标题】:Resizing UIView in runtime在运行时调整 UIView 的大小
【发布时间】:2018-04-17 08:31:52
【问题描述】:

我有一个 UIView,它在我的故事板中垂直和水平居中,并且具有固定的 height (100) 和 width (300)。现在我希望 uiview 在运行时调整大小 (100, 100)。

到目前为止,我已经尝试过,但没有任何效果。

let cgRect = CGRect(x: 0, y: 0, width: 100, height: 100)

sampleView.draw(cgRect)

和

sampleView.frame = CGRect(x: 0, y: 0, width: 100, height: 100)

和

sampleView.frame.size.height = 100
sampleView.frame.size.width = 100

【问题讨论】:

  • 检查您是否使用自动布局,这可能是问题
  • 您是否在情节提要中设置了布局约束?如果是这样,您必须设置约束...
  • 只有垂直和水平居中和固定的宽度和高度,没有别的
  • 删除任何约束,或将约束添加为出口并修改其常量
  • 正如@ReinierMelian 提到的,您是否使用了约束?

标签: ios swift


【解决方案1】:

将宽度和高度约束挂钩为 IBOutlet 和 in

@IBAction func btnClicked(_ sender: Any) {

    self.widthCon.constant = 100

    self.heightCon.constant = 100

    self.view.layoutIfNeeded()
}

【讨论】:

  • 如果只有在我按下按钮时才会调整大小怎么办?
【解决方案2】:

要在运行时期间通过按钮更改约束,您需要将其添加到IBAction。为了动画改变而不是仅仅跳跃,将代码放在UIView animation方法中:

@IBAction func buttonPressed() {

    self.widthCon.constant = 100

    self.heightCon.constant = 100

    UIView.animate(withDuration: 0.3, animations: {
        self.view.layoutIfNeeded()
    })
}

【讨论】:

    【解决方案3】:

    你可以这样做:

    override func layoutSubviews() {
        super.layoutSubviews()
        // set hight and width by constraints.
    }
    

    或:

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        // set hight and width by constraints.
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-29
      • 2014-09-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-22
      • 1970-01-01
      相关资源
      最近更新 更多