从自定义UIView类设置视图宽度约束不更新帧

问题描述 投票:0回答:1

我有一个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个回答
2
投票

你需要.isActive = true

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

另外要更改宽度需要创建宽度var

var widthCon:NSLayoutConstraint!

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

然后改变常数

widthCon.constant = /// some value 
self.superview!.layoutIfNeeded()
© www.soinside.com 2019 - 2024. All rights reserved.