ios - 无法以编程方式更改 View 的大小

标签 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 和其他地方看到的不同解决方案,但没有任何效果。它总是保持这样: enter image description here

最佳答案

你需要加上 widthAnchor & heightAnchor

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)
]) 

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

关于ios - 无法以编程方式更改 View 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55433228/

相关文章:

ios - Google ios 注册迁移到 MainTabBarController

ios - 使用 PHFetchResult 的 `enumerateObjectsUsingBlock` 时出现编译器错误

ios - 将标签连接到 UITableViewCell

ios - 第二次加载 UIView 后 NSConstraints 使应用程序崩溃

ios - 受宽度和纵横比限制的 View ,不更新高度

iOS7 - enabledRemoteNotificationTypes 返回 UIRemoteNotificationTypeNone 但在 Settings.app Alert、Badge 和 Sound 中启用

ios UIButton触摸取消

swift - 有没有比使用 switch 语句更好的方法来快速访问变量的不同属性?

ios - 启动时出现黑屏、纺车

添加 UINavigationBar 时 Swift 约束错误