在 UIView 子类中更改 NSLayoutConstraint

Change NSLayoutConstraint within UIView Subclass

我正在尝试影响 UIView 子类中的 NSLayoutConstraint。然而,无论我把代码放在哪里,它似乎都没有改变自动布局约束。
我以前使用过 NSLayoutConstraint 很多次,但由于某种原因似乎无法在子类中引用它。

我的约束是

self.ripHeight.constant

连接者

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *ripHeight;

我在initawakeFromNib方法中试过如下

- (id)init {
    self = [super init];
    if (self) {

        //self.ripHeight.constant = 100;

    }
    return self;
}

-(void)awakeFromNib {

    [super awakeFromNib];

    // 2 . Change Height of Ripll Container to suit device - bitch
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    CGFloat screenWidth = screenRect.size.width;

    //Create Nib Frame
    CGRect frameRect = self.frame;
    frameRect.size.width = screenWidth;
    frameRect.size.height = screenWidth * 1.3333;
    self.frame = frameRect;

    self.ripHeight.constant = 100;

}

我正在加载视图

[self.ripContainer addSubview:customView];

更改约束后尝试手动更新布局:

-(void)awakeFromNib {

    [super awakeFromNib];
    //...
    //your code for constraint

    [self.superview setNeedsLayout];
}

- setNeedsLayout

Invalidates the current layout of the receiver and triggers a layout update during the next update cycle.

Discussion

Call this method on your application’s main thread when you want to adjust the layout of a view’s subviews. This method makes a note of the request and returns immediately. Because this method does not force an immediate update, but instead waits for the next update cycle, you can use it to invalidate the layout of multiple views before any of those views are updated. This behavior allows you to consolidate all of your layout updates to one update cycle, which is usually better for performance.

解决此类问题的可能方法是使用 awakeAfterUsingCoder
它用作占位符视图。在此处而不是在 ViewController 中加载您的视图。还在 XIB 中设置布局约束。

有关详细信息,请参阅 this link。