子类中的Swift约束

子类中的Swift约束

本文介绍了子类中的Swift约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否存在一种从子类访问约束的方法.我有一个自定义视图.我不确定是否可以访问已经在UI中设置的约束,所以我尝试仅从子类本身创建约束.

I was wondering if there was a way to access constraints from a subclass. I have a custom view. I'm not sure if I can access the constraint I already have set in the UI, so I tried just creating the constraint from the subclass itself.

class PerformanceView: UIView {
    func initialize() {
        let heightConstraint = NSLayoutConstraint(item: self, attribute: .Height, relatedBy: .Equal, toItem: superview, attribute: .Height, multiplier: 0.47, constant: 0);
        superview.addConstraint(heightConstraint)
    }
}

上面的代码不完整.只是显示我正在尝试做的事情.有两个问题.

The above code is not complete. Just showing what I was attempting to do. So two questions.

1)我可以从子类访问UI约束吗?2)如果不是,我如何在子类中创建一个高度约束,该高度约束是Superview高度的一半.

1) Can I access a constraint on the UI from the subclass.2) If not, how can I create a height constraint in the subclass that is half of the superview height.

我确实将PerformanceView作为View的类,因为您可以看到它们都在左侧显示Performance View.其中4个.

And I do have PerformanceView as the class for the View as you can see they all say Performance View in the left. 4 of them.

推荐答案

如果我正确理解了您的问题,答案是肯定的,有一种方法.您只需使用助手编辑器将插座将您的约束拖到PerformanceView中即可.

If I understand your question correctly, the answer is yes, there is a way. You can simply drag outlets to your constraints into your PerformanceView using the Assistant Editor.

作为附件-您可以使用.constant修改代码中的约束.不过目前尚不支持修改优先级.

As an adjunct - you can modify your constraints in code by using .constant. Modifying priorities is currently not supported though.

heightConstraint.constant = 230.0 //or any other value

为了拖动出口,您必须确保在情节提要编辑器中正确标识了PerformanceView.因此,在左列中选择PerformanceView.然后在右栏中的突出显示的字段中键入"PerformanceView",如下所示,然后按回车键.现在,您应该可以上班了.

In order for dragging outlets you have to make sure that you identified your PerformanceView properly in the storyboard editor. So select your PerformanceView in the left column. Then type "PerformanceView" into the highlighted field in the right column as shown below and hit return. Now you should be good to go.

这篇关于子类中的Swift约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 08:01