向UIButton添加子视图

5
我正在尝试将一个自定义徽章添加为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];

我要添加子视图的按钮是_MsgHeadBtn,它是下面屏幕截图左上方的电子邮件图标。我试图让自定义徽标出现在电子邮件图标的稍微上方和右侧,但最终结果如屏幕截图所示!有人能提供任何建议吗?请帮忙查看一下我哪里错了!
2个回答

5

问题出现在你的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, 0, customBadge1.frame.size.width, customBadge1.frame.size.height)]; - sergio
@sergio:谢谢你的信息。我刚刚修改了我的答案 :) - Midhun MP
@Dancer:非常愉快,当您添加子视图时,它的框架将基于其父视图的框架进行计算。 - Midhun MP
@Dancer:如果被点击,你可以在IBAction方法中使用-(IBAction)click:(UIButton *)sender{//sender是被点击的按钮}获取实例。 - Midhun MP

1

请按照以下方式调整您的框架:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接