如何在ImageView的不同角落对齐textLabel

How to align textLabel in different corners of ImageView

我是Swift的新手。

基本上,我试图根据用户输入(TopRight、TopLeft、BottomRight、BottomLeft)将 textLabel 对齐到 imageView 的不同角落...但是,as you can see here,确实发生了一些奇怪的事情从一个角落换到另一个角落时。这是我的代码(我使用的是 switch 语句):

case .DownLeft:
        
        textLabel.translatesAutoresizingMaskIntoConstraints = false
        
        textLabel.leadingAnchor.constraint(equalTo: imageView.leadingAnchor).isActive = true
        textLabel.bottomAnchor.constraint(equalTo: imageView.bottomAnchor).isActive = true
        
case .DownRight:
        
        textLabel.translatesAutoresizingMaskIntoConstraints = false
        
        textLabel.trailingAnchor.constraint(equalTo: imageView.trailingAnchor).isActive = true
        textLabel.bottomAnchor.constraint(equalTo: imageView.bottomAnchor).isActive = true
        
case .UpLeft:
        
        textLabel.translatesAutoresizingMaskIntoConstraints = false
        
        textLabel.topAnchor.constraint(equalTo: imageView.topAnchor).isActive = true
        textLabel.leadingAnchor.constraint(equalTo: imageView.leadingAnchor).isActive = true
        
case .UpRight:
        
        textLabel.translatesAutoresizingMaskIntoConstraints = false
        
        textLabel.trailingAnchor.constraint(equalTo: imageView.trailingAnchor).isActive = true
        textLabel.topAnchor.constraint(equalTo: imageView.topAnchor).isActive = true

这可能是因为我需要停用或删除不再需要的约束。所以我尝试使用以下功能之一来停用约束,但到目前为止没有成功

.isActive = false

textLabel.removeFromSuperview()

textLabel.removeConstraints(textLabel.constraints)

接下来我可以尝试什么?

It may due to the fact I need to deactivate or remove constraints that I do not need anymore

完全正确。创建约束时,您需要做的不仅仅是说 .isActive = true。您每次都在创建约束 并将其丢弃 。您需要保留对您激活的每个约束的引用,以便您以后可以停用它。这叫未雨绸缪!

假设您有一个实例 属性 constraintsArray,它是一个 NSLayoutConstraint 数组。然后,例如,您有:

textLabel.leadingAnchor.constraint(equalTo: imageView.leadingAnchor).isActive = true

你会说:

self.constraintsArray.forEach { [=11=].isActive = false }
self.constraintsArray = []
let c1 = textLabel.leadingAnchor.constraint(equalTo: imageView.leadingAnchor)
c1.isActive = true
self.constraintsArray.append(c1)

使用那种逻辑,想法是每次情况发生变化时,停用所有已保存的约束,删除所有已保存的约束,然后创建新的约束并将它们添加到已保存的约束列表中下次