将子视图添加到UIButton

时间:2013-10-31 11:03:36

标签: ios objective-c uibutton addsubview

我正在尝试添加一个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];

我正在尝试添加子视图的按钮是_MsgHeadBtn,这是下面屏幕截图顶部LH上的电子邮件图标。 我试图让自定义徽章在电子邮件图标的上方和右侧略微显示 - 但我最终得到了屏幕截图中的结果!

enter image description here

任何人都可以提出任何关于我哪里出错的建议!?

2 个答案:

答案 0 :(得分: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];

答案 1 :(得分: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)];