美文网首页
NSTextView

NSTextView

作者: 皮蛋豆腐酱油 | 来源:发表于2019-10-30 16:29 被阅读0次

一.定义

多行文字输入控件,NSTextView与iOS的UITextView不同,它内中控件组成没有加入滚动条和自动滚动等,所以在使用时经常与NSScrollView一同出现

二.协议<NSTextViewDelegate>

- (BOOL)textShouldBeginEditing:(NSText *)textObject {
    return YES;  //允许接收输入
}
- (BOOL)textShouldEndEditing:(NSText *)textObject {
    return YES;  //允许结束输入
}
- (void)textDidBeginEditing:(NSNotification *)notification {
    NSTextView *textView = notification.object;
}
- (void)textDidEndEditing:(NSNotification *)notification {
}
- (void)textDidChange:(NSNotification *)notification {
  //文字内容改变响应
}

三.带滚动条的TextView

    NSScrollView *scrollView = [[NSScrollView alloc] initWithFrame:NSMakeRect(20, 150, 400, 100)];
    [scrollView setHasVerticalScroller:YES];
    [scrollView setHasHorizontalScroller:NO];
    [scrollView setBorderType:NSLineBorder];
    [scrollView setDrawsBackground:NO];
    [scrollView setHorizontalScrollElasticity:NSScrollElasticityNone];
    
    _textView = [[NSTextView alloc] initWithFrame:NSMakeRect(0, 0, 400, 100)];
    [_textView setDrawsBackground:NO];
    [_textView setTextColor:[NSColor blackColor]];
    [_textView setFont:[NSFont systemFontOfSize:12]];
    [_textView setMinSize:NSMakeSize(400, 100)];
    [_textView setMaxSize:NSMakeSize(400, FLT_MAX)];
    [_textView setVerticallyResizable:YES];
    [_textView setHorizontallyResizable:NO];
    [_textView setAutomaticLinkDetectionEnabled:NO];
    [_textView setUsesFontPanel:NO];
    [[_textView textContainer] setContainerSize:NSMakeSize(400, FLT_MAX)];
    [[_textView textContainer] setWidthTracksTextView:YES];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:4.0];
    [_textView setDefaultParagraphStyle:paragraphStyle];
    [scrollView setDocumentView:_textView];
    [self.window.contentView addSubview:scrollView];

四.带placeholder的textview

https://stackoverflow.com/questions/29428594/set-the-placeholder-string-for-nstextview

五.字数大于xxx不能输入

- (BOOL)textView:(NSTextView *)textView shouldChangeTextInRanges:(NSArray<NSValue *> *)affectedRanges replacementStrings:(nullable NSArray<NSString *> *)replacementStrings {
    if (textView == self.textView) {
        if (replacementStrings.count == 0) return YES;
        
        NSInteger existedLength = textView.string.length;
        NSInteger selectedLength = affectedRanges.lastObject.rangeValue.length;
        NSInteger replaceLength = replacementStrings.lastObject.length;
        if (existedLength - selectedLength + replaceLength > 500) {
            return NO; //字数大于500则不能输入,但是可以删除后在输入
        }
    }
    return YES;
    
}

相关文章

网友评论

      本文标题:NSTextView

      本文链接:https://www.haomeiwen.com/subject/xlzovctx.html