gpt4 book ai didi

ios - 无法以编程方式在 swift 中设置 NSLayoutConstraint 乘数...“无法分配给此表达式的结果

转载 作者:搜寻专家 更新时间:2023-10-30 21:57:19 31 4
gpt4 key购买 nike

我正在尝试以编程方式在 swift 中为乘数设置约束,当我设置值时,它只会给我错误,“无法分配给该表达式的结果”...

我用 IBOutlet 声明了 NSLayoutConstraint,然后设置乘数,就像我对另一个常量所做的一样,效果很好,但这个不会接受它...

@IBOutlet weak var clockWidthConstraint: NSLayoutConstraint!

override func updateViewConstraints() {
super.updateViewConstraints()

confirmTopConstraint.constant = 40.0
clockWidthConstraint.multiplier = 0.1 // Gives me the error!

}

有什么想法吗?

最佳答案

是的,是 read only:

var multiplier: CGFloat { get } 

您只能在创建时指定乘数。相反,您可以在运行时更改非常量 constant 属性:

var constant: CGFloat

编辑:

这需要一点努力,但要更改不可变属性,您必须创建一个新约束并复制除要更改的属性以外的所有内容。为此,我一直在尝试不同的技术,但目前正在探索这种形式:

let constraint = self.aspectRatioConstraint.with() {
(inout c:NSLayoutConstraint.Model) in
c.multiplier = self.aspectRatio }

或在更现实的环境中使用:

var aspectRatio:CGFloat = 1.0 { didSet {

// remove, update, and add constraint
self.removeConstraint(self.aspectRatioConstraint)
self.aspectRatioConstraint = self.aspectRatioConstraint.with() {
(inout c:NSLayoutConstraint.Model) in
c.multiplier = self.aspectRatio }
self.addConstraint(self.aspectRatioConstraint)
self.setNeedsLayout()
}}

支持代码在哪里:

extension NSLayoutConstraint {

class Model {

init(item view1: UIView, attribute attr1: NSLayoutAttribute,
relatedBy relation: NSLayoutRelation,
toItem view2: UIView?, attribute attr2: NSLayoutAttribute,
multiplier: CGFloat, constant c: CGFloat,
priority:UILayoutPriority = 1000) {
self.firstItem = view1
self.firstAttribute = attr1
self.relation = relation
self.secondItem = view2
self.secondAttribute = attr2
self.multiplier = multiplier
self.constant = c
self.priority = priority
}

var firstItem:UIView
var firstAttribute:NSLayoutAttribute
var relation:NSLayoutRelation
var secondItem:UIView?
var secondAttribute:NSLayoutAttribute
var multiplier:CGFloat = 1.0
var constant:CGFloat = 0
var priority:UILayoutPriority = 1000
}


func priority(priority:UILayoutPriority) -> NSLayoutConstraint {
self.priority = priority;
return self
}

func with(configure:(inout Model)->()) -> NSLayoutConstraint {

// build and configure model
var m = Model(
item: self.firstItem as! UIView, attribute: self.firstAttribute,
relatedBy: self.relation,
toItem: self.secondItem as? UIView, attribute: self.secondAttribute,
multiplier: self.multiplier, constant: self.constant)
configure(&m)

// build and return contraint from model
var constraint = NSLayoutConstraint(
item: m.firstItem, attribute: m.firstAttribute,
relatedBy: m.relation,
toItem: m.secondItem, attribute: m.secondAttribute,
multiplier: m.multiplier, constant: m.constant)
return constraint
}
}

关于ios - 无法以编程方式在 swift 中设置 NSLayoutConstraint 乘数...“无法分配给此表达式的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27870540/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com