Swift Constraints in Subclass

大憨熊 提交于 2019-12-12 03:44:23

问题


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) 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.

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.


回答1:


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.

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

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.




回答2:


make sure you add your custom class to your UIView in your storyboard

under class type in your custom class - PerformanceView

create the connection variable to hold the constraint from your storyboard

@IBOutlet weak var heightConstraint:NSLayoutConstraint?

then right click and drag the connection




回答3:


If you're looking to add @IBOutlet from IB to UIView subview, it would appear that the standard trick of control-dragging from the control down to the source code in the assistance editor doesn't work.

Sometimes IB gets confused with outlets, but fortunately, there are other ways to add outlets and these other mechanisms seem to work fine. For example, you can manually add the @IBOutlet code to your PerformanceView:

class PerformanceView: UIView {

    @IBOutlet weak var heightConstraint: NSLayoutConstraint!

}

Now you can drag from the empty connector dot in the left margin next to the @IBOutlet up to the constraint:

Or, alternatively, control-click on the PerformanceView in the document outline, and then drag from the outlet listed in the popup to the constraint:



来源:https://stackoverflow.com/questions/37735590/swift-constraints-in-subclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!