在iPhone的屏幕尺寸上更改UIButton的大小

时间:2015-05-20 15:41:58

标签: iphone swift uibutton autolayout

我想更改自动布局功能所在的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)
    }

1 个答案:

答案 0 :(得分: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))