我试图在Swift中绕过UIBarButtonItem(在大多数应用程序中都看到这种通知计数器)。我知道该怎么做,但实际上只有在将的宽度设置为34并将高度设置为24 时,它实际上才是圆形的。这些是UIBarButtonItems的魔术数字吗?如果我为其他设置宽度或高度(相同,我希望的帧为30 x 30),然后根据宽度计算 cornerRadius ,则不是完美的圆形,而是圆角的矩形。我做错了什么?我的代码如下:
let button = UIButton(type: .custom)
button.frame = CGRect(x: 0, y: 0, width: 34, height: 24)
button.backgroundColor = DarkModeUtil.isDarkMode() ? UIColor.white : UIColor.black
button.setTitle("\(self.pickedAppActions.count > 9 ? "9+" : "\(self.pickedAppActions.count)")", for: .normal)
button.setTitleColor(DarkModeUtil.isDarkMode() ? .black : UIColor.white, for: .normal)
button.contentHorizontalAlignment = .center
button.titleLabel?.fitSize()
button.layer.cornerRadius = button.bounds.size.width / 2
button.clipsToBounds = true
button.addTarget(self, action: #selector(counterTapped(_:)), for: [.touchUpInside])
let doneItem = UIBarButtonItem(image: UIImage(named: "done")?.withRenderingMode(.alwaysTemplate), style: .plain, target: self, action: #selector(doneButtonClicked(_:)))
doneItem.tintColor = DarkModeUtil.isDarkMode() ? .white : .black
let counterButton = UIBarButtonItem(customView: button)
let buttons:[UIBarButtonItem] = [doneItem,counterButton]
self.navigationItem.rightBarButtonItems = buttons
如果我设置了相同的宽度和高度,例如30 x 30,则会得到如下所示的按钮:
最佳答案
使高度和宽度34对我有用。这是一个代码。也无需更改button.frame.size.width / 2
。
let button = UIButton(type: .custom)
button.frame = CGRect(x: 0, y: 0, width: 34, height: 34)
button.backgroundColor = DarkModeUtil.isDarkMode() ? UIColor.white : UIColor.black
button.setTitle("\(self.pickedAppActions.count > 9 ? "9+" : "\(self.pickedAppActions.count)")", for: .normal)
button.setTitleColor(DarkModeUtil.isDarkMode() ? .black : UIColor.white, for: .normal)
button.contentHorizontalAlignment = .center
button.titleLabel?.fitSize()
button.layer.cornerRadius = button.bounds.size.width / 2
button.clipsToBounds = true
button.addTarget(self, action: #selector(counterTapped(_:)), for: [.touchUpInside])
let doneItem = UIBarButtonItem(image: UIImage(named: "done")?.withRenderingMode(.alwaysTemplate), style: .plain, target: self, action: #selector(doneButtonClicked(_:)))
doneItem.tintColor = DarkModeUtil.isDarkMode() ? .white : .black
let counterButton = UIBarButtonItem(customView: button)
let buttons:[UIBarButtonItem] = [doneItem,counterButton]
self.navigationItem.rightBarButtonItems = buttons
关于ios - Swift中的圆形UIBarButtonItems,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59927614/