这是我的代码:
int i = 0;
self.userInteractionEnabled = YES;
self.exclusiveTouch = YES;
self.canCancelContentTouches = YES;
self.delaysContentTouches = YES;
self.translatesAutoresizingMaskIntoConstraints = YES;
UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gototest)];
tapGestureRecognizer.numberOfTapsRequired = 1;
[self addGestureRecognizer:tapGestureRecognizer];
for (NSString *message in self.messages) {
UILabel * label = [[UILabel alloc] initWithFrame:CGRectZero];
self.userInteractionEnabled = YES;
label.text = message;
label.tag = i;
CGSize size = [message sizeWithFont:label.font];
CGFloat width = size.width + kPADDING;
label.frame = CGRectMake(xPos, 0.0, width, self.frame.size.height);
[self addSubview:label];
i++;
xPos += width;
NSLog(@"%@",NSStringFromCGRect(label.frame));
}
self.messagesWidth = xPos;
self.contentSize = CGSizeMake(xPos, self.frame.size.height);
self.contentOffset = CGPointMake(-self.frame.size.width, 0.0);
}
-(void)gototest
{
NSLog(@"test %@",@"ccc ");
}
然后为选框 - (无效)去{
if (!self.period) self.period = self.messagesWidth / 100;
// so it always takes about the same (fudged, but reasonable) amount of time to scroll the whole array
[UIView animateWithDuration:self.period
delay:0.0
options:UIViewAnimationOptionCurveLinear |UIViewAnimationOptionRepeat
animations:^{
self.contentOffset = CGPointMake(self.messagesWidth, 0.0);
} completion:^(BOOL finished){}];
}
所以,我的目标是为新闻创建一个选框,每个新闻都可以点击,以查看所点击的新内容的详细信息。
但是UITapGestureRecognizer不起作用,我不知道为什么。
请注意,self是scrollview,因为我的类是从UIScrollView扩展的。
所以请帮帮我
答案 0 :(得分:0)
您必须以下列方式继承UIScrollView
。然后使用自定义滚动视图(即TouchScrollView
)代替常规UIScrollView
<强> TouchScrollView.h:强>
#import <Foundation/Foundation.h>
@import UIKit;
@interface TouchScrollView : UIScrollView
@end
<强> TouchScrollView.m:强>
#import "TouchScrollView.h"
@implementation TouchScrollView
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// Respond to touch events here
// ...
[self.nextResponder touchesBegan:touches withEvent:event];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
[self.nextResponder touchesMoved:touches withEvent:event];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[self.nextResponder touchesEnded:touches withEvent:event];
}
@end
或者如果你想在Swift中这样做,因为它现在是时尚:
<强> TouchScrollView.swift 强>
import Foundation
import UIKit
class TouchScrollView: UIScrollView {
override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
// Respond to touch events here
// ...
nextResponder().touchesBegan(touches, withEvent: event)
}
override func touchesMoved(touches: NSSet!, withEvent event: UIEvent!) {
nextResponder().touchesMoved(touches, withEvent: event)
}
override func touchesEnded(touches: NSSet!, withEvent event: UIEvent!) {
nextResponder().touchesEnded(touches, withEvent: event)
}
}