我希望我的按钮位于我的footerView的中心。我尝试了几种方法,但每次都失败了:
1
application = UIApplication 0x0000000131d07800
launchOptions = [UIApplicationLaunchOptionsKey : Any]? nil
self = App.AppDelegate 0x00000001c403ac20
storyboard (UIStoryboard)
intialViewcontroller (UIViewController)
barFont UIFont
使用自动布局,这会使我的按钮居中,但会打破它的宽度和高度,我将其设置为30以上。
override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footerView = UIView(frame: CGRect.zero)
footerView.backgroundColor = UIColor(rgba: "#F9FAFB")
let button = UIButton(frame: CGRect(x:(footerView.frame.size.width - 30) / 2, y:(footerView.frame.size.height - 30) / 2, width: 30, height: 30)) button.setImage(UIImage(named: "gen-cog"), for: .normal)
button.addTarget(self, action: #selector(footerButtonAction), for: .touchUpInside)
footerView.addSubview(button)
}
3
let centerYCon = NSLayoutConstraint(item: button,
attribute: .centerY,
relatedBy: .equal,
toItem: footerView,
attribute: .centerY,
multiplier: 1.0,
constant: 0.0);
footerView.addConstraint(centerYCon)
let centerXCon = NSLayoutConstraint(item: button,
attribute: .centerX,
relatedBy: .equal,
toItem: footerView,
attribute: .centerX,
multiplier: 1.0,
constant: 0.0);
footerView.addConstraint(centerXCon)
footerView.addSubview(button)
答案 0 :(得分:1)
button.translatesAutoresizingMaskIntoConstraints = false
footerView.addSubview(button)
现在添加两个额外的约束。
let widthConstraint = NSLayoutConstraint(item: button, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 30)
let heightConstraint = NSLayoutConstraint(item: button, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 30)
button.addConstraints([widthConstraint, heightConstraint])