本文主要是介绍UITextView接收左右点击事件。,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在一个UITextView中, 为了使其接收点击事件,如在这个UITextView的左边点一下,或者右边点一下,能接收到这个事件,可用于,比如一个看小说的应用,可以上下滚动看这一集的其它内容,而在页面上左边或者右边点击,以进行上一章或下一章小说的浏览, 这个时候就需要用到这个UITextView了。
其它不说了, 直接上代码:
(一):在一个UIViewController中加入了一个UITextView,并把这个UITextView的delegate指向了这个UIViewController。
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UITextView *myTextView = [[UITextView alloc] initWithFrame:self.view.bounds];
myTextView.font = [UIFont boldSystemFontOfSize:21.0f];
myTextView.editable = NO;
myTextView.delegate = self;
myTextView.text = @"都是问候语,不同的是相互问候的人之间的熟稔程度,以及答话方式\
How do you do? 你好吗?说话的两人初次相识,而且在是在比较正式的场合下。答:How do you do.\
How are you? 你好吗?说话的人相互认识。答:I'm fine, thank you. And you?\
How are you doing? 你最近怎样?说话的人不仅认识,还比较熟。回答的时候可以具体一点,如:Not too bad, I just moved to a new place.都是问候语,不同的是相互问候的人之间的熟稔程度,以及答话方式\
How do you do? 你好吗?说话的两人初次相识,而且在是在比较正式的场合下。答:How do you do.\
How are you? 你好吗?说话的人相互认识。答:I'm fine, thank you. And you?\
How are you doing? 你最近怎样?说话的人不仅认识,还比较熟。回答的时候可以具体一点,如:Not too bad, I just moved to a new place.";
[self.view addSubview:myTextView];
}
(二)然后添加了一个类别文件如下:
头文件内容:
#import <Foundation/Foundation.h>
@interface UITextView (AddNotif)
@end
实现文件内容:
#import "TesCate.h"
@implementation UITextView (AddNotif)
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[[self nextResponder] touchesBegan:touches withEvent:event];
[super touchesBegan:touches withEvent:event];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
[[self nextResponder] touchesMoved:touches withEvent:event];
[super touchesMoved:touches withEvent:event];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touchPint = [touches anyObject];
// 取这个点点击的位置是在左边还是右边,并向delegate发出事件
CGPoint clickedPoint = [touchPint locationInView:self];
if (clickedPoint.x > self.frame.size.width/2) {
NSLog(@"Right");
if ([self.delegate respondsToSelector:@selector(clickRightDetect:)]) {
[self.delegate clickRightDetect:YES];
}
}else {
if ([self.delegate respondsToSelector:@selector(clickRightDetect:)]) {
[self.delegate clickRightDetect:NO];
}
NSLog(@"Left");
}
[[self nextResponder] touchesEnded:touches withEvent:event];
[super touchesEnded:touches withEvent:event];
}
@end
(三)然后在这个UIViewController实现文件中,实现下面这个方法:
#pragma mark
- (void)clickRightDetect:(BOOL)isRightClick {
if (isRightClick == YES) {
NSLog(@"Right part clicked");
}else {
NSLog(@"Left part clicked");
}
}
(四)运行程序,可以发现这个UITextView因为内容较多,而可以自然上下滚动,再在左边或者右边点击,发现可以接收到点击事件。
可在这个点击事件中,实现上翻页或下翻页的效果。
这篇关于UITextView接收左右点击事件。的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!