【问题标题】:Setting view width constraint from custom UIView class not updating frames从自定义 UIView 类设置视图宽度约束不更新帧
【发布时间】:2019-04-14 15:44:47
【问题描述】:

我有一个 UIView,我想在其中通过使用百分比来确定宽度来获得一个简单的加载器视图。

我已经完成了百分比代码,我知道它正在工作。

但是我在设置视图的宽度约束时遇到了麻烦。我通过获取框架宽度并将其乘以百分比来找到宽度。我知道它的宽度合适。但我似乎无法从这个函数中设置约束。

我的 UIView 子类中的代码如下所示:

func initSubviews() {
    // in here i do some other stuff and have an asyncronous call to an api
    // so then I've got this code calling the next function
    DispatchQueue.main.async {
        self.setCompletionWidth(nextTimer: nextTimer!, oldDate: oldDate!)
    }
}

func setCompletionWidth(nextTimer: Date, oldDate: Date) {
   let date = Date()

   // calculatePercent returns something like 0.49
   let percent = calculatePercent(middleDate: date, endDate: nextTimer, originalDate: oldDate)

   //this is returning a correct value
   let width = (self.frame.width)*percent

// completionView is the view I'm trying to change the width of
   self.completionView.widthAnchor.constraint(equalToConstant: width)
   self.layoutSubviews()
}

发生的事情是 completionView 没有得到正确的宽度。 我也试过 setCompletionWidth 函数

self.completionView.widthAnchor.constraint(equalToConstant: width)
containerView.layoutSubviews()

UIView.animate(withDuration: 0.2) {
    self.completionView.widthAnchor.constraint(equalToConstant: width)
    self.containerView.layoutSubviews()
    //also tried self.layoutSubviews here
}

self.layoutIfNeeded()
self.completionView.widthAnchor.constraint(equalToConstant: width)
self.layoutIfNeeded()

我希望 completionView 的宽度大约是 150,但实际上它是 350,这是它原来的宽度。

我认为发生的事情是在我将约束设置为不同的值后视图没有更新。但是,我无法终生更新它。我想在这里得到一些帮助。

【问题讨论】:

    标签: swift autolayout nib


    【解决方案1】:

    你需要.isActive = true

    self.completionView.widthAnchor.constraint(equalToConstant: width).isActive = true
    

    还要更改宽度,您需要创建一个宽度变量,例如

    var widthCon:NSLayoutConstraint!
    

    widthCon =  self.completionView.widthAnchor.constraint(equalToConstant: width)
    widthCon.isActive = true
    

    然后用

    改变常数
    widthCon.constant = /// some value 
    self.superview!.layoutIfNeeded()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 2019-04-19
      相关资源
      最近更新 更多