添加一个子视图到UIButton

我试图添加一个customBadge作为UIButton的子视图 –

这是我的代码到目前为止 –

//msg count initiaition //CustomBadge *customBadge1 = [CustomBadge customBadgeWithString:@"2"]; CustomBadge *customBadge1 = [CustomBadge customBadgeWithString:@"2" withStringColor:[UIColor whiteColor] withInsetColor:[UIColor redColor] withBadgeFrame:YES withBadgeFrameColor:[UIColor redColor] withScale:2.0 withShining:YES]; // Set Position of Badge 1 [customBadge1 setFrame:CGRectMake(self.view.frame.size.width/2-customBadge1.frame.size.width/2+_MsgHeadBtn.frame.size.width/2, 110, customBadge1.frame.size.width, customBadge1.frame.size.height)]; //add badge to view [_MsgHeadBtn addSubview:customBadge1]; 

我试图添加子视图的button是_MsgHeadBtn,这是下面截图顶部LH的电子邮件图标。 我试图让自定义徽章在电子邮件图标的右侧显示轻微,但最终会在截图中显示结果!

在这里输入图像说明

任何人都可以提供任何意见,我要去哪里错了!

问题在你的setFrame:方法中。 您正在使用self.view.frame.size.width

检查这个代码:

 [customBadge1 setCenter:CGPointMake(_MsgHeadBtn.frame.size.width, 0)]; [_MsgHeadBtn addSubview:customBadge1]; 

要么

 [customBadge1 setFrame:CGRectMake(_MsgHeadBtn.frame.size.width, 0, customBadge1.frame.size.width, customBadge1.frame.size.height)]; [_MsgHeadBtn addSubview:customBadge1]; 

调整你的框架如下:

 [customBadge1 setFrame:CGRectMake(_MsgHeadBtn.frame.size.width-customBadge1.frame.size.width,-customBadge1.frame.size.height/2, customBadge1.frame.size.width, customBadge1.frame.size.height)];