How to Create layout constraints programmatically

前端 未结 5 626
-上瘾入骨i
-上瘾入骨i 2020-11-27 02:41

I am displaying a view in the bottom of the universal application and adding this view dynamically in my view. I want to show this view in bottom every time like iAd. in bot

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 03:05

    Also since iOS 9 it could be done super simple with anchors:

    Swift 3

    extension UIView {
    
        func addConstaintsToSuperview(leadingOffset: CGFloat, topOffset: CGFloat) {
    
            guard superview != nil else {
                return
            }
    
            translatesAutoresizingMaskIntoConstraints = false
    
            leadingAnchor.constraint(equalTo: superview!.leadingAnchor,
                                     constant: leadingOffset).isActive = true
    
            topAnchor.constraint(equalTo: superview!.topAnchor,
                                 constant: topOffset).isActive = true
        }
    
        func addConstaints(height: CGFloat, width: CGFloat) {
    
            heightAnchor.constraint(equalToConstant: height).isActive = true
            widthAnchor.constraint(equalToConstant: width).isActive = true
        }
    
    }
    

    OBJC category

    @implementation UIView (Constraints)
    
    -(void)addConstaintsToSuperviewWithLeadingOffset:(CGFloat)leadingOffset topOffset:(CGFloat)topOffset
    {
        if (self.superview == nil) {
            return;
        }
    
        self.translatesAutoresizingMaskIntoConstraints = false;
    
        [[self.leadingAnchor constraintEqualToAnchor:self.superview.leadingAnchor
                                            constant:leadingOffset] setActive:true];
    
        [[self.topAnchor constraintEqualToAnchor:self.superview.topAnchor
                                       constant:topOffset] setActive:true];
    }
    
    -(void)addConstaintsWithHeight:(CGFloat)height width:(CGFloat)width
    {
        [[self.heightAnchor constraintEqualToConstant:height] setActive:true];
        [[self.widthAnchor constraintEqualToConstant:width] setActive:true];
    }
    
    @end
    

提交回复
热议问题