快速更新约束

2023-11-24

我将约束添加到我的创建的按钮中UIView

func CreateButtonWithIndex(index:Int) {

    newButton.setTranslatesAutoresizingMaskIntoConstraints(false)

    self.view.addSubview(newButton)

    let newButtonConstraintL = NSLayoutConstraint(item: newButton, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 50)
    let newButtonConstraintH = NSLayoutConstraint(item: newButton, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 50)
    var newButtonConstraintX = NSLayoutConstraint(item: newButton, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: CGFloat(riga))
    var newButtonConstraintY = NSLayoutConstraint(item: newButton, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 1, constant: CGFloat(colonna))

    view.addConstraints([newButtonConstraintX,newButtonConstraintY,newButtonConstraintH,newButtonConstraintL])

    var pan = UIPanGestureRecognizer(target:self, action:"pan:")
    pan.maximumNumberOfTouches = 2
    pan.minimumNumberOfTouches = 1
    newButton.addGestureRecognizer(pan)
}

func pan(rec:UIPanGestureRecognizer) {
  case .Ended: 
        if let subview = selectedView {
            if let button = rec.view as? UIButton {
                if let title = button.titleForState(.Normal){
                    button.setTranslatesAutoresizingMaskIntoConstraints(false)
                    let line = Float(p.x % snapX)
                    let column = Float(p.x % snapY)
                    let constraintL = NSLayoutConstraint(item: button, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 50)
                    let constraintH = NSLayoutConstraint(item: button, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 50)
                    var constraint2 = NSLayoutConstraint(item: button, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: CGFloat(line))
                    var constraint3 = NSLayoutConstraint(item: button, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 1, constant: CGFloat(column))

                    view.addConstraints([constraint2,constraint3,constraintL.constraintH])
                }
            }
        }
}

在我的项目中,我的用户可以移动这些按钮,然后我尝试向识别的按钮添加更多约束,但我只是得到无尽的错误约束

  "<NSLayoutConstraint:0x7f8e5a4e9450 UIButton:0x7f8e5a644f60'Button6'.centerX == UIView:0x7f8e5a648bc0.centerX - 120>",
  "<NSLayoutConstraint:0x7f8e5a5be040 'UIView-Encapsulated-Layout-Width' H:[UIView:0x7f8e5a648bc0(736)]>",
  "<NSAutoresizingMaskLayoutConstraint:0x7f8e5a5be1f0 h=-&- v=-&- 'UIView-Encapsulated-Layout-Left' H:|-(0)-[UIView:0x7f8e5a648bc0]   (Names: '|':UITransitionView:0x7f8e5a5a8190 )>",
  "<NSAutoresizingMaskLayoutConstraint:0x7f8e5a5b53b0 h=--& v=--& UIButton:0x7f8e5a644f60'Button6'.midX == + 200>"

将尝试通过打破约束来恢复

"<NSLayoutConstraint:0x7f8e5a4e9450 UIButton:0x7f8e5a644f60'Button6'.centerX == UIView:0x7f8e5a648bc0.centerX - 120>"

"<NSLayoutConstraint:0x7f8e5a4e9510 UIButton:0x7f8e5a644f60'Button6'.centerY == UIView:0x7f8e5a648bc0.centerY - 40>",
"<NSLayoutConstraint:0x7f8e5a5be1a0 'UIView-Encapsulated-Layout-Height' V:[UIView:0x7f8e5a648bc0(414)]>",
"<NSAutoresizingMaskLayoutConstraint:0x7f8e5a5be240 h=-&- v=-&- 'UIView-Encapsulated-Layout-Top' V:|-(0)-[UIView:0x7f8e5a648bc0]   (Names: '|':UITransitionView:0x7f8e5a5a8190 )>",
"<NSAutoresizingMaskLayoutConstraint:0x7f8e5a5b82d0 h=--& v=--& UIButton:0x7f8e5a644f60'Button6'.midY == + 189>"

将尝试通过打破约束来恢复

<NSLayoutConstraint:0x7f8e5a4e9510 UIButton:0x7f8e5a644f60'Button6'.centerY == UIView:0x7f8e5a648bc0.centerY - 40>

...我应该更新 newButtonConstraintX / Y 但我不明白如何做到这一点?


问题是您添加的新约束与现有约束冲突。

您有几个选择:

  1. 从 iOS 8 开始,您可以设置active财产给false在添加新约束之前先检查约束。

  2. 在 8 之前的 iOS 版本中,您需要在添加新约束之前删除旧约束。

  3. 理想情况下,最好不必激活/停用(或者更糟糕的是添加和删除)约束,而只需修改constant单一约束的性质。例如在 Swift 3/4 中:

    class ViewController: UIViewController {
    
        private var xConstraint: NSLayoutConstraint!
        private var yConstraint: NSLayoutConstraint!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            let label = UILabel()
            label.text = "x"
            label.translatesAutoresizingMaskIntoConstraints = false
            view.addSubview(label)
    
            // I don't really need to save references to these, so these are local variables
    
            let widthConstraint = label.widthAnchor.constraint(equalToConstant: 50)
            let heightConstraint = label.heightAnchor.constraint(equalToConstant: 50)
    
            // but since I'll be modifying these later, these are class properties
    
            xConstraint = label.centerXAnchor.constraint(equalTo: view.centerXAnchor)
            yConstraint = label.centerYAnchor.constraint(equalTo: view.centerYAnchor)
    
            NSLayoutConstraint.activate([widthConstraint, heightConstraint, xConstraint, yConstraint])
    
            let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:)))
            view.addGestureRecognizer(pan)
        }
    
        private var originalCenter: CGPoint!
    
        @objc func handlePan(_ gesture: UIPanGestureRecognizer) {
            if gesture.state == .began {
                originalCenter = CGPoint(x: xConstraint.constant, y: yConstraint.constant)
            }
    
            let translation = gesture.translation(in: gesture.view!)
    
            xConstraint.constant = originalCenter.x + translation.x
            yConstraint.constant = originalCenter.y + translation.y
        }
    
    }
    

    当修改可以达到想要的效果时constant的约束,这通常是最好的。

对于 Swift 2 语法,请参阅此答案的先前修订版.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

快速更新约束 的相关文章

随机推荐

  • 为什么 Xcode 构建配置的精确副本会失败?

    我有一个react native具有桥接 Swift 代码的应用程序 可以使用 Xcode 毫无问题地构建 运行和存档10 0使用默认的Release and Debug构建配置 我用Xcode gt Product gt Archive或
  • 如何叠加不同单元格的图?

    在我笔记本的一个单元格中 我已经用以下内容绘制了一些内容 myplot plt figure plt plot x y 现在 在不同的单元格中 我想再次绘制完全相同的图形 但在其顶部添加新的图形 类似于两次连续调用所发生的情况 plt pl
  • 角度材质 - 更改单击的垫列表选项的颜色

    是否可以更改选中复选框的默认颜色 mat pseudo checkbox checked
  • preg_match_all() [function.preg-match-all]: 未知修饰符 ']'

    使用了几种不同的模式 但它们都出现了这个错误 那么出了什么问题呢 我要诊断的最短的一个是 pattern
  • 为什么使用“*”构建视图不好?

    为什么使用 构建视图不好 假设您有一个复杂的联接 并且所有字段都可能在某处使用 然后您只需选择所需的字段即可 SELECT field1 field2 FROM aview WHERE 视图 aview 可以是SELECT table1 t
  • 不需要导出仅包含虚拟/内联函数的类?

    在 Win32 上的 C 中 假设我有一个带有声明类的头文件的 DLL DLL 导出一些获取该类实例的指针 引用的方法 例如工厂函数 我是否正确地认为 如果只在其实例上调用虚拟或内联函数 则无需使用 declspec 将该类标记为导出 相反
  • 导入错误:无法导入名称 _imaging

    我安装了Pillow 然后我想做 from PIL import Image 我收到以下错误 Traceback most recent call last File
  • 如何在 MySQL 中搜索嵌套 JSON

    我使用 MySQL 5 7 和本机 JSON 数据类型 样本数据 code 2 stores code 100 quantity 2 code 200 quantity 3 code 4 stores code 300 quantity 4
  • 将同一对象两次添加到 ManyToManyField

    我有两个 Django 模型类 class A models Model name models CharField max length 128 irrelevant class B models Model a models ManyT
  • Mac OS X shell 实用程序,显示多核系统中各个 CPU 的使用情况

    我一直在寻找一个 osx 实用程序来显示每个 cpu 的 cpu 使用情况 例如 中央处理器 0 10 中央处理器 1 2 我知道有很多方法可以在其他类 Unix 系统 proc mpstat 等 中获取此信息 但在 osx 中都不起作用
  • 检查对象数组是否包含某个键

    我需要确定对象数组中是否存在某个键 这是一个示例数组 arrOfObj mainKey1 subKey1 innerKey1 innerMostKey1 key1 value mainKey2 key2 value mainKe
  • 如何使用 Javascript 下载、压缩和保存多个文件并获得进度?

    我正在创建一个 Chrome 扩展程序 需要从网站下载多个文件 图像和 或视频 这些文件可能很大 所以我想向用户显示下载进度 经过一番研究 我发现目前可能的解决方案可能是 使用 XMLHttpRequests 下载所有文件 下载后 使用 J
  • Hibernate:flush() 和 commit()

    打电话是个好习惯吗org hibernate Session flush 分别地 正如中所述org hibernate Session docs 必须在工作单元结束时 提交事务并关闭会话之前调用 根据刷新模式 Transaction com
  • Java 中的 for 循环如何检查其条件?

    我的问题与当存在 print 语句时 java 检查 for 循环条件的顺序有关in循环的 条件 这似乎是一件不切实际的事情 我从未见过它以任何实际的方式使用过 尽管我对打印内容缺乏理解 这让我认为我可能不完全理解 for 循环的功能 最近
  • nextjs13 中所有 mui 组件上的“使用客户端”是什么?

    我是 React nextjs 开发的新手 一直认为反应组件在服务器中渲染并准备好缓存 但是 如果 nextjs 13 将所有 mui 控件作为客户端组件 渲染将在哪里发生 客户端 正如你所看到的 即使对于 2 行 React 的做法也是
  • 如何在 Javascript 中对英文和中文混合进行字数统计

    我想统计一篇包含英文和中文的文章中有多少个单词 对于英语来说 这很简单 每个词都是一个词 对于中文 我们将每个字符算作一个单词 因此 香港人在这里是三个词 例如 我是香港人 的字数应该为 6 知道如何在 Javascript jQuery
  • 图片未显示在推送通知中

    我正在使用下面的通知有效负载并使用 Postman 向 Android 设备发送推送通知 to topics xxxx data url https res cloudinary com demo image upload w 200 la
  • 未找到 ClientBuilder 类

    我正在尝试使用 Jersey 框架构建 RESTFul 客户端 因此我添加了以下类 import javax ws rs client Client import javax ws rs client ClientBuilder publi
  • “不是 git 存储库”

    我正在尝试使用一个使用 git 作为后备存储的程序 我是 git 的新手 在初始化时 该程序执行以下操作 git bare rev parse refs heads index 结果是 fatal Not a git repository
  • 快速更新约束

    我将约束添加到我的创建的按钮中UIView func CreateButtonWithIndex index Int newButton setTranslatesAutoresizingMaskIntoConstraints false