2015-05-20 114 views
0

我想更改自动布局功能所在的UIButton的大小(宽度,高度)。以下是自动布局功能关闭时正常工作的代码。自动布局功能开启时,我应该做些什么改变代码。更改iPhone屏幕大小的UIButton的大小

println("height : \(height)") 
    println("width : \(width)") 
    if (height == 460) 
    { 
     btn1.frame = CGRectMake(22, 66, 40, 40) 
     //btn1.sizeToFit() 

     //btn1.frame = CGRectMake(200, 200, 100, 100) 
     println("480") 
     self.view.addSubview(btn1) 
    } 
    else if (height == 548) 
    { 
     btn1.frame = CGRectMake(22, 66, 60, 60) 


     //btn1.frame.size.height = 65; 
     //CGRect frame = btn1.frame; 
     //btn1.frame.size.height = btn1.frame.size.height-20; 
     //btn1.frame = CGRectMake(200, 200, 100, 100) 
     println("548") 
     //btn1.sizeToFit() 
     //self.view.addSubview(btn1) 
    } 
    else 
    { 
     //btn1.sizeToFit() 
     btn1.frame = CGRectMake(22, 66, 75, 75) 
     //btn1.frame = CGRectMake(200, 200, 100, 100) 
     println("647") 
     self.view.addSubview(btn1) 
    } 
+0

检查此问题http://stackoverflow.com/questions/30300015/modifying-constraints/30301168#30301168 –

回答

0

您需要以编程方式添加约束。

// After initialize button 
btn1.setTranslatesAutoresizingMaskIntoConstraints(false) 
self.view.addSubView(btn1) 

// Left 
self.view.addConstraint(NSLayoutConstraint(item: btn1, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 22)) 

// Top 
self.view.addConstraint(NSLayoutConstraint(item: btn1, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 66)) 

// Width 
btn1.addConstraint(NSLayoutConstraint(item: btn1, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 60)) 

// Height 
btn1.addConstraint(NSLayoutConstraint(item: btn1, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 60))