-(void) viewdidload {[Super viewdidload]; UIButton *btntest = [UIButton buttonwithtype:uibuttontypecustom];//does not need to deliberately specify X, y coordinates, you can use Cgrectzero Btntest.backgroundcolor = [Uicolor Redcolor]; BtnTest.layer.borderColor = [Uicolor Yellowcolor]. Cgcolor; BtnTest.layer.borderWidth = 2.0; [Self.view Addsubview:btntest]; [Btntest settranslatesautoresizingmaskintoconstraints:no];//will use AutoLayout to layout the top of the//btntest top relative to the self.view with a distance of 100 Nslayoutconstraint *constrainttop = [Nslayoutconstraint constraintwithitem:btntest attribute:NSLayoutAttributeTop Relatedby:nslayoutrelationequal ToItem:self.view attribute:nslayoutattributetop multiplier:1.0 constant:100]; The left side of btntest relative to Self.view is nslayoutconstraint *constraintleft = [Nslayoutconstraint constraintwithitem: btntest attribute:nslayoutattributeleft relatedby:nslayoutrelationequal toItem:self.view attribute: Nslayoutattributeleft multiplier:1.0 constant:100]; Right side of btntest relative to Self.view is a distance of NslayoutcoNstraint *constraintright = [Nslayoutconstraint constraintWithItem:self.view attribute:nslayoutattributeright Relatedby:nslayoutrelationequal toitem:btntest attribute:nslayoutattributeright multiplier:1.0 constant:100]; The bottom distance of the btntest bottom relative to Self.view is nslayoutconstraint *constraintbottom = [Nslayoutconstraint constraintwithitem: Self.view attribute:nslayoutattributebottom relatedby:nslayoutrelationequal toitem:btntest attribute: Nslayoutattributebottom multiplier:1.0 constant:100]; Horizontally centered Nslayoutconstraint *constraintxcenter = [Nslayoutconstraint constraintwithitem:btntest attribute: Nslayoutattributecenterx relatedby:nslayoutrelationequal ToItem:self.view Attribute:nslayoutattributecenterx multiplier:1.0 constant:00.0f]; Center vertically Nslayoutconstraint *constraintycenter = [Nslayoutconstraint constraintwithitem:btntest attribute: Nslayoutattributecentery relatedby:nslayoutrelationequal ToItem:self.view Attribute:nslayoutattributecentery multiplier:1.0 constant:00.0f]; Add a constraint to the parent view [Self.view Addconstraint:constrainttop]; [Self.view Addconstraint:constraintleft]; [Self.view Addconstraint:constraintright]; [Self.view Addconstraint:constraintbottom]; [Self.view Addconstraint:constraintxcenter]; [Self.view Addconstraint:constraintycenter]; }
iOS manually added view is used in code (auto layout) AutoLayout