【问题标题】:Changing UIButton frame disconnects it from IBAction selector更改 UIButton 框架会将其与 IBAction 选择器断开连接
【发布时间】:2017-01-20 22:44:49
【问题描述】:

我有一个包含UIButton 的 xib 文件。我控制+拖动按钮来创建一个动作。按钮的位置必须动态设置。下面的方法是从更新按钮位置的drawRect: 方法调用的。

-(void)updateButtonPosition {
    CGFloat xPos = self.label.frame.origin.x + self.label.frame.size.width;
    CGFloat yPos = self.label.frame.origin.y + self.label.frame.size.height - 25;
    CGRect frame = CGRectMake(xPos, yPos, self.button.frame.size.width, self.button.frame.size.height);
    self.button.frame = frame;
}

但我注意到调用此函数会将UIButton 与我通过控制+拖动创建的操作断开连接(即,当我在应用程序运行时单击按钮时没有任何反应)。我评论了调用此函数的部分。现在按钮开始工作并调用了操作方法。因此,更改框架断开 UIButton 与其操作方法。

编辑:为其所有超级视图启用用户交互。我没有使用自动布局。项目就是这样。

如何更改按钮的框架,以便在单击按钮时也调用该操作?

【问题讨论】:

  • 试着把你的按钮放在前面。
  • 它已经在最前面了。
  • 你怎么知道它是disconneted?该动作是否已完全删除?我几乎不相信这种方法会做这样的事情,所以你能详细说明一下吗?当您更新边界时更有可能将按钮放在其超级视图边界之外。
  • @holex 看我的回答。
  • @oye,不用感谢我的帮助 :)

标签: ios objective-c uibutton drawrect ibaction


【解决方案1】:

检查按钮的框架与它的超级视图框架。按钮仅在其位于其父视图框架内时才会接收触摸事件。

【讨论】:

    【解决方案2】:

    无法重现您的问题,我拖动了一个名为“btnAction”的操作和一个名为“btnTest”的插座。

    这是 ViewController.h

    #import <UIKit/UIKit.h>
    
    @interface ViewController : UIViewController
    
    - (IBAction)btnAction:(id)sender;
    @property (weak, nonatomic) IBOutlet UIButton *btnTest;
    
    @end
    

    这是 ViewController.m

    #import "ViewController.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
    //    [super viewDidLoad];
    //    // Do any additional setup after loading the view, typically from a nib.
    
        [self.view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(grHandler)]];
    }
    
    -(void)grHandler{
        NSLog(@"grHandler actived.");
        [self updateButtonPosition];
    }
    
    - (IBAction)btnAction:(id)sender {
        NSLog(@"btn actived.");
    }
    
    -(void)updateButtonPosition {
        CGFloat xPos = 20;
        CGFloat yPos = 30;
        CGRect frame = CGRectMake(xPos, yPos, self.btnTest.frame.size.width, self.btnTest.frame.size.height);
        self.btnTest.frame = frame;
    }
    
    @end
    

    尝试使用我的代码并告诉我问题出在哪里?

    那我可以帮你。

    【讨论】:

    • Action 方法正在运行,但从未调用过 grHandler。你能确认一下吗?
    • 正常工作。我不得不点击视图。 :D 我仍然不知道问题是什么。这是我的项目ufile.io/d6411
    • 获取不到你的代码文件,能不能放到GitHub上,那我就不用下载了。
    • 终于明白了。
    【解决方案3】:

    我的按钮框架位于其父视图的框架之外。因此它无法点击。

    更多信息请参考UIButton not responding after set frame within UIScrollview

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多