无法以编程方式更改视图的大小

时间:2019-03-30 15:58:19

标签: ios swift nslayoutconstraint

我有一个UIButton,我尝试通过编程方式更改它的大小,但是它没有任何作用。 这是我写的:

import UIKit

class HomeVC: UIViewController {

let addGroupBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
let addGroupLabel = UILabel()

override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = UIColor(red: 110/255, green: 178/255, blue: 87/255, alpha: 1.0)
    setAddGroupBtn()
}

func setAddGroupBtn(){
    addGroupBtn.setImage(UIImage(named: "addIcon"), for: .normal)
    addGroupBtn.addTarget(self, action: #selector(moveToAddGroup), for: .touchUpInside)
    addGroupBtn.translatesAutoresizingMaskIntoConstraints = false

    self.view.addSubview(addGroupBtn)

    addGroupBtn.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: 50).isActive = true
    addGroupBtn.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor, constant: 14).isActive = true
}

func setAddGroupLabel(){
    addGroupLabel.translatesAutoresizingMaskIntoConstraints = false
    addGroupLabel.text = "Add Group"
}

@objc func moveToAddGroup(){
    print("ADD GROUP")
    //Move to another VC
}
}

我在Stackoverflow和其他地方尝试了几种不同的解决方案,但是没有任何效果。它总是这样: findLast

1 个答案:

答案 0 :(得分:1)

您需要加widthAnchorheightAnchor

NSLayoutConstraint.activate([
    addGroupBtn.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: 50),
    addGroupBtn.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor, constant: 14),
    addGroupBtn.widthAnchor.constraint(equalToConstant:50),
    addGroupBtn.heightAnchor.constraint(equalToConstant:50)
]) 

由于按钮具有固有的内容大小,因此可以根据其内容进行拉伸