You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将通知角标移动到UIButton左侧紧邻的位置

问题原因及解决方案

核心问题1:代码执行顺序错误

你当前的代码执行逻辑存在顺序问题:

  • 你调用[profileBadge setFrame:CGRectMake(-8.0, -4.0, 14.0, 14.0)]以及[profileBadge.superview bringSubviewToFront:profileBadge]时,profileBadge还没有被添加到Button上,superview为nil,这两行代码此时完全不生效。
  • 后续你将profileBadge添加到Button后,也没有重新设置frame,导致你设置的x轴偏移没有生效。

核心问题2:M13BadgeView自带对齐属性覆盖手动frame

你设置了profileBadge.horizontalAlignment = M13BadgeViewHorizontalAlignmentRight,M13BadgeView内部会根据对齐属性自动计算角标的位置,你手动设置的frame的x值会被库的内部布局逻辑覆盖,自然无法调整左右位置。


修正后的代码示例
profileBadge= [[BadgeView alloc] initWithFrame:CGRectMake(0, 0, 14.0, 14.0)];

profileBadge.font = badgeFont;
// 关闭自带的水平对齐,改为手动控制位置
profileBadge.horizontalAlignment = M13BadgeViewHorizontalAlignmentNone;
profileBadge.verticalAlignment = M13BadgeViewVerticalAlignmentNone;
profileBadge.badgeBackgroundColor = [UIColor redColor];
profileBadge.text = @"";
profileBadge.hidden = YES;

// 先调整按钮边距、添加角标
Button.contentEdgeInsets = UIEdgeInsetsMake(0, 14, 0, 8);
[Button addSubview:profileBadge];
// 添加完成后再设置frame、调整层级
[profileBadge setFrame:CGRectMake(-8.0, -4.0, 14.0, 14.0)];
[profileBadge.superview bringSubviewToFront:profileBadge];

// 确认按钮不会裁剪超出范围的内容
Button.clipsToBounds = NO;

补充说明

如果修改后还是有位置偏差,可以在按钮的layoutSubviews方法(或者按钮所在UIViewController的viewDidLayoutSubviews方法)中重新设置profileBadge的frame,避免导航栏布局变动覆盖你设置的位置。

内容的提问来源于stack exchange,提问作者stefanosn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 04:45:03