NSScrollView

Open Xcode and make a new Cocoa Application, click next, name it „NSScrollView“ and create it to your favorite location.

Now select the MainMenu.xib file on the right hand side and add a „Text View“ from the Object Lib.

Add the Text View

Connect it to the AppDelegate.h

Add this code to the AppDelegate.m file within the applicationDidFinishLaunching method

NSSize contentSize = [myScrollView contentSize];

NSTextView *theTextView = [[NSTextView alloc] initWithFrame:NSMakeRect(0, 0, contentSize.width, contentSize.height)];

NSString *aString = [[NSString alloc]init];

aString = @“Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce et mauris tempus massa scelerisque condimentum. Aliquam elementum, leo at porttitor congue, velit quam semper turpis, vel sodales lectus neque a risus. Fusce vulputate odio eget magna consequat condimentum. Aenean nulla metus, placerat sit amet blandit eget, vulputate vel eros. Mauris eget nisi eu orci elementum tincidunt. Fusce accumsan dapibus vulputate. Mauris rhoncus sem sit amet nisi dapibus iaculis. Mauris vel turpis at neque dignissim tincidunt. Duis faucibus massa venenatis massa tincidunt sed gravida mauris sodales. Curabitur et sapien ut magna ultrices accumsan ut at nunc. Donec vehicula, dui vel volutpat cursus, dui enim scelerisque risus, sit amet mattis ante lacus cursus tellus. Mauris lobortis aliquam vestibulum. Suspendisse tincidunt diam vitae felis eleifend in vehicula leo lobortis. Donec porttitor lorem in nulla fringilla iaculis. Quisque sodales imperdiet libero, nec pulvinar justo fringilla vel. Maecenas in nunc turpis.“;

[theTextView setString:aString];    //add aString to theTextView

[theTextView setEditable:NO];   //don’t allow to edit theTextView by the user, change it if you want

[myScrollView setDocumentView:theTextView];   //add theTextView to the scrollView

NSRange endRange = NSMakeRange([[theTextView string] length], 0);   //get the end of the textView by determing the stringlenght
[theTextView scrollRangeToVisible:endRange];    //scroll down to the end

And don’t forget to synthesize it at the top of the file. To do this type

@synthesize myScrollView;

The whole file should look like this

Final code

To run the application click „Run“ or use „cmd + r“

After the application did build an started you will see this final result

If you don’t want to copy and paste all the code you can download the code here

Advertisements