【问题标题】:addSubView to UIButton将子视图添加到 UIButton
【发布时间】:2011-10-04 06:01:36
【问题描述】:

我正在尝试将子视图添加到 UIButton。这现在工作正常。但是一旦我添加了子视图,该按钮就无法再点击了。

我使用以下代码:

UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(column*100+24, row*80+10, 64, 64);
[button addSubview:asyncImage];
[button addSubview:price];
    [button addTarget:self 
               action:@selector(buttonClicked:) 
     forControlEvents:UIControlEventTouchUpInside];

如果我剪掉 2 个 addsubviews,该按钮将再次起作用。如果有人知道如何解决这个问题,那就太好了!

THNX!!!

【问题讨论】:

    标签: iphone objective-c ios uibutton addsubview


    【解决方案1】:

    我找到了一个快速的解决方案。我需要将 asyncimageview 设置为以下内容:

    asyncImage.userInteractionEnabled = NO;
            asyncImage.exclusiveTouch = NO;
    

    在这之后它起作用了!

    【讨论】:

    • 尽可能在 2 天内回答我的问题
    • 我对“userInteractionEnabled”属性的看法正好相反,我认为将其设置为“YES”实际上应该在按钮的子视图上捕获点击事件。很好的答案!
    • 简单地设置 userInteractionEnabled = false 对我有用。
    【解决方案2】:

    尝试:

    [UIButton buttonWithType:UIButtonTypeCustom];

    代替:

    [UIButton buttonWithType:UIButtonControlType];

    【讨论】:

    • 这不起作用,它给我一个错误,不识别 UIButtonControlType
    • 哦,然后尝试将用户交互设置为启用,像这样 [YOUR BUTTON setUserInteractionEnabled://bool,对你来说是的
    • 我尝试了 2 个子视图(价格和 asyncImage)和按钮。位没有任何区别......
    【解决方案3】:

    你有没有试过把:

    [asyncImage setUserInteractionEnabled:YES];
    

    【讨论】:

    • 您是否也尝试过其他视图? [价格 setUserInteractionEnabled:YES];
    【解决方案4】:

    在同一情况下,我执行此操作: 从 UIButton 继承并将按钮的所有标签和图像视图添加到 self,最后将新按钮作为最后一个子视图查看,并将 self 按钮的目标添加到最后一个按钮(还将 backgroundColor 设置为 clearColor 以实现透明)。现在它可以点击并且可以正常工作了。

    【讨论】:

    • 我以某种方式得到了这个想法,但不完全知道我需要做什么。你有一个简短的例子吗?谢谢!
    • 我主要不明白你的意思是让动作从 UIButton 继承,并将其设置为 self.如果我做 self.button 它会给我一个错误。谢谢!
    • 哇,好的!要试试看!谢谢
    【解决方案5】:

    这里重要的是确保将userInteractionEnabled 设置为NO。幸运的是,它立即适用于UIImageViewUILabel(可能适用于UIView 的其他子类,但这些是添加到按钮的最流行的子视图),因为默认情况下,此类的默认设置为NO。不幸的是,它在UIView 中设置为YES,因此请确保在这种情况下更改它。没有必要与任何其他标志混在一起。问题的本质是很多人不知道这个标志的默认值在子类中是不同的。

    【讨论】:

    • @benhi,很酷。如果您希望我提供帮助 - 更多详细信息会有所帮助:P
    • Julian @property (weak, nonatomic) IBOutlet UIButton *popular;流行 = [UIButton buttonWithType:UIButtonTypeCustom]; UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, popular.frame.size.width, popular.frame.size.height)]; label.text = @"ButtonTitle"; label.textColor = [UIColor redColor];标签.userInteractionEnabled = 否; [流行的addSubview:label];
    • 所以它没有检测到触摸或什么不起作用?
    • 标签没有出现
    • 你给它什么帧,可能是宽高都是0?你确定那个时候按钮已经初​​始化了吗?顺便说一句,这里不显示的标签有点离题;)因为这里的问题是添加的子视图禁用了触摸
    【解决方案6】:

    在 Swift 中,测试你的 UIButton 是否被屏蔽

    uibtn.userInteractionEnabled = false
    uibtn.exclusiveTouch = false
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-20
      • 1970-01-01
      • 2013-11-11
      • 1970-01-01
      • 2018-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多