Swift 从自定义UIView类设置视图宽度约束不更新框架
我有一个UIView,其中我希望通过使用百分比来确定宽度,从而获得一个简单的加载程序视图 我已经完成了百分比代码,我知道它正在工作 但是,设置视图的宽度约束时遇到问题。我通过获取帧宽度并将其乘以百分比来计算宽度。我知道它的宽度合适。但我似乎无法从这个函数设置约束 在我的UIView子类中,我的代码如下所示:Swift 从自定义UIView类设置视图宽度约束不更新框架,swift,autolayout,nib,Swift,Autolayout,Nib,我有一个UIView,其中我希望通过使用百分比来确定宽度,从而获得一个简单的加载程序视图 我已经完成了百分比代码,我知道它正在工作 但是,设置视图的宽度约束时遇到问题。我通过获取帧宽度并将其乘以百分比来计算宽度。我知道它的宽度合适。但我似乎无法从这个函数设置约束 在我的UIView子类中,我的代码如下所示: func initSubviews() { // in here i do some other stuff and have an asyncronous call to an a
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()
及
及
我希望completionView的宽度大约是150,但实际上是350,这是它原来的宽度
我认为现在的情况是,在我将约束设置为不同的值之后,视图没有更新。然而,我无法用我的生命去更新它。我想在这里得到一些帮助。您需要
。isActive=true
self.completionView.widthAnchor.constraint(equalToConstant: width).isActive = true
还要更改宽度,您需要创建一个宽度变量,如
var widthCon:NSLayoutConstraint!
然后用
widthCon.constant = /// some value
self.superview!.layoutIfNeeded()
您需要
.isActive=true
self.completionView.widthAnchor.constraint(equalToConstant: width).isActive = true
还要更改宽度,您需要创建一个宽度变量,如
var widthCon:NSLayoutConstraint!
然后用
widthCon.constant = /// some value
self.superview!.layoutIfNeeded()