【问题标题】:Adding a subview to UIButton向 UIButton 添加子视图
【发布时间】:2013-11-11 08:30:58
【问题描述】:

我正在尝试将 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,它是下面屏幕截图左上方的电子邮件图标。 我试图让自定义徽章略微显示在电子邮件图标的上方和右侧 - 但我最终得到了屏幕截图中的结果!

谁能提供任何关于我哪里出错的建议!?

【问题讨论】:

    标签: ios objective-c uibutton addsubview


    【解决方案1】:

    问题出在您的 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:感谢您提供的信息。我刚刚修改了我的答案:)
    • @Dancer:很高兴,当你添加子视图时,它的框架将根据它的父框架计算。
    • @Dancer:如果被点击,可以在IBAction方法中使用-(IBAction)click:(UIButton *)sender{//sender是被点击的按钮}
    【解决方案2】:

    如下调整你的框架:

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

    【讨论】:

      猜你喜欢
      • 2016-07-14
      • 1970-01-01
      • 2011-10-04
      • 1970-01-01
      • 1970-01-01
      • 2012-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多