如何修改UIButton图片而不重置其位置?拖拽按钮场景问题
这个坑我之前踩过!你遇到的问题本质是:当调用setImage(_:for:)时,UIButton会根据新图片的尺寸自动调整自身的frame,这就把你拖拽后设置的center给覆盖重置了。下面给你几个靠谱的解决办法,按推荐程度排序:
1. 提前固定按钮的尺寸(最推荐)
在初始化menuButton的时候,就给它设置固定的宽高,不管图片怎么换,按钮的尺寸都不变,自然不会触发位置重置。
如果用frame布局:
// 初始化按钮时设置固定大小 menuButton = UIButton(type: .custom) menuButton.frame = CGRect(x: initialX, y: initialY, width: 60, height: 60) // 替换成你需要的尺寸 menuButton.isUserInteractionEnabled = true // 然后添加手势...
如果用AutoLayout:
menuButton = UIButton(type: .custom) menuButton.translatesAutoresizingMaskIntoConstraints = false // 添加宽高约束 NSLayoutConstraint.activate([ menuButton.widthAnchor.constraint(equalToConstant: 60), menuButton.heightAnchor.constraint(equalToConstant: 60) ]) // 其他初始化操作...
2. 设置图片前后手动保存并恢复位置
如果暂时不想改布局,可以在设置图片前先把当前的center存下来,设置完图片后再手动赋值回去,强制保持位置:
@objc func draggedButton(_ sender:UIPanGestureRecognizer){ self.view.bringSubview(toFront: menuButton) let translation = sender.translation(in: self.view) menuButton.center = CGPoint(x: menuButton.center.x + translation.x, y: menuButton.center.y + translation.y) sender.setTranslation(CGPoint.zero, in: self.view) if menuButton.center.x < 100 { // 保存当前位置 let currentCenter = menuButton.center menuButton.setImage(UIImage(named: "newimage"), for: .normal) // 恢复位置 menuButton.center = currentCenter } }
3. 调整按钮的 autoresizingMask
如果你的按钮是用 autoresizing 布局的,可以把它的 autoresizingMask 设置成不会自动调整位置的类型,避免图片变化时系统自动修改center:
menuButton.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin]
额外提示
建议优先用第一种方法,固定尺寸不仅能解决位置重置问题,还能让按钮的UI表现更一致,不管后续换什么图片都不会乱跳。
内容的提问来源于stack exchange,提问作者CL So
相关产品推荐
相关产品推荐

