Displaying text in a NSScrollView (Swift)

前端 未结 7 1600
醉酒成梦
醉酒成梦 2020-12-10 05:14

Just started to learn Swift and created a little macOS app in which I want to use a NSScrollView to display an attributed String. I’ve tried:

@I         


        
7条回答
  •  我在风中等你
    2020-12-10 05:39

    Apple's has an article about setting up a text view inside a scroll view programmatically. Text System User Interface Layer Programming Guide: Putting an NSTextView Object in an NSScrollView You should read that for greatest understanding, but here's the code:

    NSScrollView *scrollview = [[NSScrollView alloc] initWithFrame:[[theWindow contentView] frame]];
    NSSize contentSize = [scrollview contentSize];
    
    [scrollview setBorderType:NSNoBorder];
    [scrollview setHasVerticalScroller:YES];
    [scrollview setHasHorizontalScroller:NO];
    [scrollview setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
    
    theTextView = [[NSTextView alloc] initWithFrame:NSMakeRect(0, 0, contentSize.width, contentSize.height)];
    [theTextView setMinSize:NSMakeSize(0.0, contentSize.height)];
    [theTextView setMaxSize:NSMakeSize(FLT_MAX, FLT_MAX)];
    [theTextView setVerticallyResizable:YES];
    [theTextView setHorizontallyResizable:NO];
    [theTextView setAutoresizingMask:NSViewWidthSizable];
    
    [[theTextView textContainer] setContainerSize:NSMakeSize(contentSize.width, FLT_MAX)];
    [[theTextView textContainer] setWidthTracksTextView:YES];
    [scrollview setDocumentView:theTextView];
    [theWindow setContentView:scrollview];
    [theWindow makeKeyAndOrderFront:nil];
    [theWindow makeFirstResponder:theTextView];
    

    You can then set the text of the text view by operating on its textStorage object:

    theTextView.textStorage.attributedString = attributedString;
    

提交回复
热议问题