【问题标题】:Can't touch UIButton behind UIScrollview无法触摸 UIScrollview 后面的 UIButton
【发布时间】:2016-04-24 22:32:49
【问题描述】:

我在UIScrollview 后面有一个UIButton,我希望能够触摸该按钮。很明显,此时我只能对UIScrollview 执行操作,但我也希望能够对UIButton 执行操作

【问题讨论】:

  • 不可能。你的按钮被滚动视图覆盖。在滚动视图出现在按钮顶部之前,您无法单击按钮
  • @BharathVankireddy 没有什么是不可能的。
  • 别着急兄弟,让你自己试试,把解决办法贴在这里,看到我也会很开心。
  • 试试 -- scrollView.userInteractionEnabled = NO; -- 但是你将无法与滚动视图交互。
  • 如果您只关心调用附加到该按钮的操作,那么您也可以手动执行此操作。 [self methodName:sender]; 但这想让你的用户触摸它。

标签: ios uiscrollview uibutton


【解决方案1】:

没有什么是不可能的” ...当然,但这可能是精神错乱。


如果您希望UIScrollView 对用户保持可触摸性,您可以尝试类似于Hemang suggests 的方法。

我建议直接通过向UIButtontouchUpInside 事件发送a 信号。例如,在您的UIViewController

@implementation ViewController {
    UIScrollView* scrollView;
    UITapGestureRecognizer* tapGesture;

    UIButton* button;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    button = [[UIButton alloc] initWithFrame:(CGRect){30, 30, 300, 300}];
    [button addTarget:self action:@selector(buttonPress) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];

    scrollView = [[UIScrollView alloc] initWithFrame:(CGRect){20, 20, 300, 500}];
    tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(scrollViewWasTouched)];
    [scrollView addGestureRecognizer:tapGesture];
    [self.view addSubview:scrollView];


}

-(void) buttonPress {
    NSLog(@"Button press!");
}

-(void) scrollViewWasTouched {
    if (CGRectContainsPoint(button.frame, [tapGesture locationOfTouch:0 inView:self.view])) {
        [button sendActionsForControlEvents:UIControlEventTouchUpInside];
    }
}

@end

我不知道你为什么曾经想要这样做!


编辑

我现在了解到您希望这样做,因为您希望滚动视图中的图像表现得像按钮。我建议您只需将 UIImageView 对象替换为 UIButton 对象即可。

然后您可以直接将图像添加到UIButton

[button setImage:image forState:UIControlStateNormal];

【讨论】:

  • 我正在使用 uiscrollview 来滚动思考图像,并且当我触摸图像时,我有一个按钮可以执行操作。
  • 这可行,但我不想在拖动 uiscrollview 时执行任何操作。这样就会发生。
  • 滚动时我的答案不会执行按钮操作。它仅在您点击时执行。但是,您是否考虑过直接将UITapGestureRecogniser 添加到UIImageView?还是将UIButton 覆盖在UIImageView 上? 更好的是,将UIImageView 替换为UIButton 并将图像直接添加到按钮中。我认为有许多解决方案并不像您要求的那样老套。
  • 这些都是很好的解决方案,这只是其中的一天,我应该休息一下,第二天来办公室。
  • 这似乎允许该方法触发按钮,但是用户仍然无法实际点击按钮,因此您没有得到任何 UI 反馈(例如按钮突出显示)“我点了它。
【解决方案2】:

你可以重写方法

override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView?

在scrollView 和Button 的superview 中。此方法应返回特定点的接收器。所以在你的情况下应该是这样的

override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? { 
if CGRectContainsPoint(button.frame, point) {
return button
}
return super.hitTest(post, withEvent: event)
}

【讨论】:

  • 是的,但是如果按钮来自 viewController,UIScrollowView 类如何知道按钮?
猜你喜欢
  • 1970-01-01
  • 2011-04-08
  • 2013-03-26
  • 1970-01-01
  • 1970-01-01
  • 2011-02-10
  • 2011-11-11
  • 2013-08-08
  • 1970-01-01
相关资源
最近更新 更多