iOS开发求助:无法通过代码修改UIButton尺寸
嘿,我懂你这会儿的郁闷——明明给UIButton设了初始frame,结果怎么调尺寸都没反应对吧?问题的根源其实和你开启的**自动布局(Auto Layout)**有关,咱们一步步捋清楚:
问题出在哪?
当你给按钮设置translatesAutoresizingMaskIntoConstraints = false时,自动布局系统就完全接管了按钮的布局逻辑,你一开始写的frame: CGRect(x: 0, y: 0, width: 50, height: 50)会被直接忽略。而你目前只给按钮加了topAnchor和leadingAnchor两个位置约束,没设置宽度和高度约束,自动布局只能跟着按钮内部的图片自动算尺寸,自然达不到你想要的50x50效果。
两种靠谱的解决方案
方案1:直接添加固定宽高约束(最稳妥)
修改你的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 // 新增宽高约束,固定按钮尺寸 addGroupBtn.widthAnchor.constraint(equalToConstant: 50).isActive = true addGroupBtn.heightAnchor.constraint(equalToConstant: 50).isActive = true }
方案2:让按钮尺寸适配图片(按需选择)
如果你希望按钮大小和图片完全匹配,可以调整按钮的内容模式,同时确保图片本身有明确尺寸:
func setAddGroupBtn(){ addGroupBtn.setImage(UIImage(named: "addIcon"), for: .normal) // 让图片在按钮内按比例适配,避免拉伸变形 addGroupBtn.imageView?.contentMode = .scaleAspectFit // 让按钮自动适配图片尺寸 addGroupBtn.sizeToFit() 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 }
不过这种方式依赖图片本身的尺寸,要是你需要固定大小的按钮,还是方案1更靠谱。
额外小提示
- 开启自动布局后,所有视图的位置和尺寸都得靠约束定义,别再依赖初始frame了
- 如果后续要动态改按钮尺寸,可以先保存约束的引用,再修改
constant值:
// 提前保存宽度约束的引用 var btnWidthConstraint: NSLayoutConstraint! // 设置约束时赋值 btnWidthConstraint = addGroupBtn.widthAnchor.constraint(equalToConstant: 50) btnWidthConstraint.isActive = true // 动态修改尺寸时 btnWidthConstraint.constant = 60
内容的提问来源于stack exchange,提问作者John Doah
相关产品推荐
相关产品推荐

