直接上代码:
#import "RootViewController.h"
#import <QuartzCore/QuartzCore.h> /// 用户视觉反馈
@interface RootViewController ()<UITextViewDelegate>
@property (nonatomic, strong) UIToolbar *toolBar ;
@property (nonatomic, strong) UITextView *textView ;
@end
@implementation RootViewController
- (UIToolbar *)toolBar {
if (!_toolBar) {
self.toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 375, 30)];
[_toolBar setBarStyle:UIBarStyleBlack];
UIBarButtonItem *oneButton = [[UIBarButtonItem alloc] initWithTitle:@"開始" style:UIBarButtonItemStyleDone target:self action:nil];
UIBarButtonItem *twoButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
UIBarButtonItem *threeButton = [[UIBarButtonItem alloc] initWithTitle:@"完毕" style:UIBarButtonItemStyleDone target:self action:@selector(handleThreeBtn)];
NSArray *buttonArray = [NSArray arrayWithObjects:oneButton, twoButton, threeButton, nil];
[_toolBar setItems:buttonArray];
}
return _toolBar;
}
- (UITextView *)textView {
if (!_textView) {
self.textView = [[UITextView alloc] initWithFrame:CGRectMake(5, 200, 375, 190)];
_textView.textColor = [UIColor redColor];
_textView.font = [UIFont systemFontOfSize:20];
_textView.delegate = self;
[_textView.layer setCornerRadius:10];
_textView.backgroundColor = [UIColor cyanColor];
_textView.text = @"sfjlegjklaeyg a";
_textView.scrollEnabled = YES;
_textView.autoresizingMask = UIViewAutoresizingFlexibleHeight ;
[_textView setInputAccessoryView:self.toolBar];
}
return _textView;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self.view addSubview:self.textView];
UIMenuItem *menuItem = [[UIMenuItem alloc] initWithTitle:@"分享到新浪微博" action:@selector(changeColor)];
UIMenuController *menu = [UIMenuController sharedMenuController];
[menu setMenuItems:[NSArray arrayWithObject:menuItem]];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#pragma mark - Action -
- (void)handleThreeBtn {
[self.textView resignFirstResponder];
}
- (void)changeColor {
self.view.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255.0 green:arc4random() % 256 / 255.0 blue:arc4random() % 256 / 255.0 alpha:1];
}
- (void)handleDone {
[self.textView resignFirstResponder];
}
#pragma mark - UITextViewDelegate -
- (void)textViewDidBeginEditing:(UITextView *)textView {
UIBarButtonItem *done = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(handleDone)];
self.navigationItem.rightBarButtonItem = done;
}
- (void)textViewDidEndEditing:(UITextView *)textView {
self.navigationItem.rightBarButtonItem = nil;
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
if ([text isEqual:@"\n"]) {
[textView resignFirstResponder];
return NO;
}
return YES;
}
@end