NSPopover show relative to NSStatusItem - objective-c

This is my code:
if #available(OSX 10.10, *) {
if let b = statusItem.button {
popover.showRelativeToRect(b.bounds, ofView: b, preferredEdge: .MinY)
}
} else {
}
The else block is for OS X Mavericks because NSStatusItem.button is not available. Is there a simple way of showing the popover relative to the status item? If not, is it possible to show the popover in the center of the screen instead without the arrow?

before you had access to the statusitem button you had to provide your own view. Then all works the same
to retain the original behaviour, draw a custom view that looks like a status item ;)
e.g.
#interface DDQuickMenuStatusItemView : NSView
#property(weak) NSStatusItem *item;
//...
#end
#implementation DDQuickMenuStatusItemView
//...
- (void)drawRect:(NSRect)dirtyRect {
NSImage *image = nil;
if(self.item) {
[self.item drawStatusBarBackgroundInRect:self.bounds withHighlight:NO];
image = self.item.image;
}
if(image) {
NSRect r = self.bounds;
r.size = [image size];
r = [self.class centerRect:r inRect:self.bounds];
r = [self centerScanRect:r];
[image drawInRect:r fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1];
}
}
#pragma mark -
+ (CGRect)centerRect:(CGRect)rect inRect:(CGRect)inRect
{
CGRect result = rect;
result.origin.x = inRect.origin.x + (inRect.size.width - result.size.width)*0.5f;
result.origin.y = inRect.origin.y + (inRect.size.height - result.size.height)*0.5f;
return result;
}
#end
Note that the view is a sample and not production ready ;)

Related

How to implement a multiline NSTokenField?

I want to implement an NSTokenField that spans multiple lines. For example:
Multi-line NSTokenField
I found a some sample code of multi-line NSTokenField on the internet:
IBOutlet NSTokenField *tokenField;
- (void)awakeFromNib
{
[[tokenField cell] setWraps:YES];
}
made my class delegate of the NSTokenField and implement the following method
- (void)controlTextDidChange:(NSNotification *)obj {
NSRect oldTokenFieldFrame = [tokenField frame];
NSRect tokenFieldBounds = [tokenField bounds];
float height = oldTokenFieldFrame.size.height;
tokenFieldBounds.size.height = CGFLOAT_MAX;
NSSize cellSize = [[tokenField cell] cellSizeForBounds:tokenFieldBounds];
float y = oldTokenFieldFrame.origin.y + height - cellSize.height;
[tokenField setFrame:NSMakeRect(oldTokenFieldFrame.origin.x,
y,
oldTokenFieldFrame.size.width,
cellSize.height)];
}
but this code does not work correctly.
Could you please help me with this issue?
Thank you in advance.
For everybody who is just looking for an answer with working code, I've found this super short solution. Here we go:
#import "MyExpandingTokenField.h"
#implementation MyExpandingTokenField
- (NSSize)intrinsicContentSize {
NSSize intrinsicContentSize = [self sizeThatFits:NSMakeSize(self.frame.size.width, CGFLOAT_MAX)];
intrinsicContentSize = NSMakeSize(intrinsicContentSize.width, intrinsicContentSize.height + 5);
return intrinsicContentSize;
}
- (void)textDidChange:(NSNotification *)notification {
[super textDidChange:notification];
[self invalidateIntrinsicContentSize];
}
#end

How to re-size UITextView when keyboard shown with iOS 7

I have a view controller which contains a full-screen UITextView. When the keyboard is shown I would like to resize the text view so that it is not hidden under the keyboard.
This is a fairly standard approach with iOS, as described in this question:
How to resize UITextView on iOS when a keyboard appears?
However, with iOS 7, if the user taps on the text view in the bottom half of the screen, when the text view resizes, the cursor remains offscreen. The text view only scrolls to bring the cursor into view if when the user hits enter.
I read the docs which talk about this very topic. I translated it into Swift and it worked absolutely beautifully for me.
This is used for a full page UITextView like iMessage.
I am using iOS 8.2 and Swift on XCode 6.2 and here's my code. Just call this setupKeyboardNotifications from your viewDidLoad or other initialization method.
func setupKeyboardNotifications() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWasShown:"), name: UIKeyboardDidShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillBeHidden:"), name: UIKeyboardWillHideNotification, object: nil)
}
func keyboardWasShown(aNotification:NSNotification) {
let info = aNotification.userInfo
let infoNSValue = info![UIKeyboardFrameBeginUserInfoKey] as NSValue
let kbSize = infoNSValue.CGRectValue().size
let contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0)
codeTextView.contentInset = contentInsets
codeTextView.scrollIndicatorInsets = contentInsets
}
func keyboardWillBeHidden(aNotification:NSNotification) {
let contentInsets = UIEdgeInsetsZero
codeTextView.contentInset = contentInsets
codeTextView.scrollIndicatorInsets = contentInsets
}
Also if you are having issues with the caret being in the right place when rotated check for the orientation change and scroll to the right position.
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
scrollToCaretInTextView(codeTextView, animated: true)
}
func scrollToCaretInTextView(textView:UITextView, animated:Bool) {
var rect = textView.caretRectForPosition(textView.selectedTextRange?.end)
rect.size.height += textView.textContainerInset.bottom
textView.scrollRectToVisible(rect, animated: animated)
}
Swift 3:
func configureKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(aNotification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(aNotification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
func keyboardWasShown(aNotification:NSNotification) {
let info = aNotification.userInfo
let infoNSValue = info![UIKeyboardFrameBeginUserInfoKey] as! NSValue
let kbSize = infoNSValue.cgRectValue.size
let contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0)
textView.contentInset = contentInsets
textView.scrollIndicatorInsets = contentInsets
}
func keyboardWillBeHidden(aNotification:NSNotification) {
let contentInsets = UIEdgeInsets.zero
textView.contentInset = contentInsets
textView.scrollIndicatorInsets = contentInsets
}
Swift 4 & 5:
func setupKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_ :)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
#objc func keyboardWillShow(_ notification:NSNotification) {
let d = notification.userInfo!
var r = (d[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
r = self.textView.convert(r, from:nil)
self.textView.contentInset.bottom = r.size.height
self.textView.verticalScrollIndicatorInsets.bottom = r.size.height
}
#objc func keyboardWillHide(_ notification:NSNotification) {
let contentInsets = UIEdgeInsets.zero
self.textView.contentInset = contentInsets
self.textView.verticalScrollIndicatorInsets = contentInsets
}
With Auto Layout, it's much easier (provided you understand Auto Layout) to handle:
Instead of trying to identify and resize the affected views, you simply create a parent frame for all your view's contents. Then, if the kbd appears, you resize the frame, and if you've set up the constraints properly, the view will re-arrange all its child views nicely. No need to fiddle with lots of hard-to-read code for this.
In fact, in a similar question I found a link to this excellent tutorial about this technique.
Also, the other examples here that do use textViewDidBeginEditing instead of the UIKeyboardWillShowNotification have one big issue:
If the user has an external bluetooth keyboard attached then the control would still get pushed up even though no on-screen keyboard appears. That's not good.
So, to summarize:
Use Auto Layout
Use the UIKeyboardWillShowNotification notification,
not the TextEditField's events for deciding when to resize your
views.
Alternatively, check out LeoNatan's reply. That might even be a cleaner and simpler solution (I've not tried myself yet).
Do not resize the text view. Instead, set the contentInset and scrollIndicatorInsets bottom to the keyboard height.
See my answer here:
https://stackoverflow.com/a/18585788/983912
Edit
I made the following changes to your sample project:
- (void)textViewDidBeginEditing:(UITextView *)textView
{
_caretVisibilityTimer = [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:#selector(_scrollCaretToVisible) userInfo:nil repeats:YES];
}
- (void)_scrollCaretToVisible
{
//This is where the cursor is at.
CGRect caretRect = [self.textView caretRectForPosition:self.textView.selectedTextRange.end];
if(CGRectEqualToRect(caretRect, _oldRect))
return;
_oldRect = caretRect;
//This is the visible rect of the textview.
CGRect visibleRect = self.textView.bounds;
visibleRect.size.height -= (self.textView.contentInset.top + self.textView.contentInset.bottom);
visibleRect.origin.y = self.textView.contentOffset.y;
//We will scroll only if the caret falls outside of the visible rect.
if(!CGRectContainsRect(visibleRect, caretRect))
{
CGPoint newOffset = self.textView.contentOffset;
newOffset.y = MAX((caretRect.origin.y + caretRect.size.height) - visibleRect.size.height + 5, 0);
[self.textView setContentOffset:newOffset animated:NO];
}
}
Removed setting old caret position at first, as well as disabled animation. Now seems to work well.
Whilst the answer given by #Divya lead me to the correct solution (so I awarded the bounty), it is not a terribly clear answer! Here it is in detail:
The standard approach to ensuring that a text view is not hidden by the on-screen keyboard is to update its frame when the keyboard is shown, as detailed in this question:
How to resize UITextView on iOS when a keyboard appears?
However, with iOS 7, if you change the text view frame within your handler for the UIKeyboardWillShowNotification notification, the cursor will remain off screen as described in this question.
The fix for this issue is to change the text view frame in response to the textViewDidBeginEditing delegate method instead:
#implementation ViewController {
CGSize _keyboardSize;
UITextView* textView;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
textView = [[UITextView alloc] initWithFrame:CGRectInset(self.view.bounds, 20.0, 20.0)]; textView.delegate = self;
textView.returnKeyType = UIReturnKeyDone;
textView.backgroundColor = [UIColor greenColor];
textView.textColor = [UIColor blackColor];
[self.view addSubview:textView];
NSMutableString *textString = [NSMutableString new];
for (int i=0; i<100; i++) {
[textString appendString:#"cheese\rpizza\rchips\r"];
}
textView.text = textString;
}
- (void)textViewDidBeginEditing:(UITextView *)textView1 {
CGRect textViewFrame = CGRectInset(self.view.bounds, 20.0, 20.0);
textViewFrame.size.height -= 216;
textView.frame = textViewFrame;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
CGRect textViewFrame = CGRectInset(self.view.bounds, 20.0, 20.0);
textView.frame = textViewFrame;
[textView endEditing:YES];
[super touchesBegan:touches withEvent:event];
}
#end
NOTE: unfortunately textViewDidBeginEdting fires before the UIKeyboardWillShowNotification notification, hence the need to hard-code the keyboard height.
Following on is working for me :
.h file
#interface ViewController : UIViewController <UITextViewDelegate> {
UITextView *textView ;
}
#property(nonatomic,strong)IBOutlet UITextView *textView;
#end
.m file
#implementation ViewController
#synthesize textView;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
CGRect textViewFrame = CGRectMake(20.0f, 20.0f, 280.0f, 424.0f);
//UITextView *textView = [[UITextView alloc] initWithFrame:textViewFrame];
textView.frame = textViewFrame;
textView.delegate = self;
textView.returnKeyType = UIReturnKeyDone;
textView.backgroundColor = [UIColor greenColor];
textView.textColor = [UIColor blackColor];
[self.view addSubview:textView];
}
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
NSLog(#"textViewShouldBeginEditing:");
return YES;
}
- (void)textViewDidBeginEditing:(UITextView *)textView1 {
NSLog(#"textViewDidBeginEditing:");
CGRect textViewFrame = CGRectMake(20.0f, 20.0f, 280.0f, 224.0f);
textView1.frame = textViewFrame;
}
- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
NSLog(#"textViewShouldEndEditing:");
return YES;
}
- (void)textViewDidEndEditing:(UITextView *)textView{
NSLog(#"textViewDidEndEditing:");
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
return YES;
}
- (void)textViewDidChange:(UITextView *)textView{
NSLog(#"textViewDidChange:");
}
- (void)textViewDidChangeSelection:(UITextView *)textView{
NSLog(#"textViewDidChangeSelection:");
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
NSLog(#"touchesBegan:withEvent:");
CGRect textViewFrame = CGRectMake(20.0f, 20.0f, 280.0f, 424.0f);
textView.frame = textViewFrame;
[self.view endEditing:YES];
[super touchesBegan:touches withEvent:event];
}
#end
i had done it and its work completely.
#define k_KEYBOARD_OFFSET 95.0
-(void)keyboardWillAppear {
// Move current view up / down with Animation
if (self.view.frame.origin.y >= 0)
{
[self moveViewUp:NO];
}
else if (self.view.frame.origin.y < 0)
{
[self moveViewUp:YES];
}
}
-(void)keyboardWillDisappear {
if (self.view.frame.origin.y >= 0)
{
[self moveViewUp:YES];
}
else if (self.view.frame.origin.y < 0)
{
[self moveViewUp:NO];
}
}
-(void)textFieldDidBeginEditing:(UITextField *)sender
{
//if ([sender isEqual:_txtPassword])
// {
//move the main view up, so the keyboard will not hide it.
if (self.view.frame.origin.y >= 0)
{
[self moveViewUp:YES];
}
//}
}
//Custom method to move the view up/down whenever the keyboard is appeared / disappeared
-(void)moveViewUp:(BOOL)bMovedUp
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.4]; // to slide the view up
CGRect rect = self.view.frame;
if (bMovedUp) {
// 1. move the origin of view up so that the text field will come above the keyboard
rect.origin.y -= k_KEYBOARD_OFFSET;
// 2. increase the height of the view to cover up the area behind the keyboard
rect.size.height += k_KEYBOARD_OFFSET;
} else {
// revert to normal state of the view.
rect.origin.y += k_KEYBOARD_OFFSET;
rect.size.height -= k_KEYBOARD_OFFSET;
}
self.view.frame = rect;
[UIView commitAnimations];
}
- (void)viewWillAppear:(BOOL)animated
{
// register keyboard notifications to appear / disappear the keyboard
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardWillAppear)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardWillDisappear)
name:UIKeyboardWillHideNotification
object:nil];
}
- (void)viewWillDisappear:(BOOL)animated
{
// unregister for keyboard notifications while moving to the other screen.
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillHideNotification
object:nil];
}
This is my solution, July 2015 using Swift 1.2 on Xcode 6.4 targeting iOS 7.1 - a combination of several approaches. Borrowed Johnston's keyboard handing Swift code. Its a bit of a hack, but its simple and it works.
I have a vanilla UITextView inside a single View.
I did not want to embed it inside a UIScrollView as per Apple's documentation. I just wanted the UITextView re-sized when software keyboard appeared, and resized to original when keyboard was dismissed.
These are the basic steps:
Set up keyboard notifications
Set up layout constraint in "Interface Builder" (TextView to bottom edge in my case)
Create an IBOutlet for this constraint in the relevant code file so you can adjust it programmatically
Use keyboard notifications to intercept events and get keyboard size
Programmatically adjust constraint IBOutlet using keyboard size to re-size TextView.
Put everything back when keyboard is dismissed.
So, onto the code.
I've set up constraint outlet at the top of the code file via the usual drag-drop in interface builder: #IBOutlet weak var myUITextViewBottomConstraint: NSLayoutConstraint!
I also set up a global variable where I can back up the state of affairs before the keyboard come up: var myUITextViewBottomConstraintBackup: CGFloat = 0
Implement keyboard notifications, call this function in viewDidLoad or any other startup/setup section:
func setupKeyboardNotifications() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWasShown:"), name: UIKeyboardDidShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillBeHidden:"), name: UIKeyboardWillHideNotification, object: nil)
}
Then these two functions will be called automatically when keyboard is shown/dismissed:
func keyboardWasShown(aNotification:NSNotification) {
let info = aNotification.userInfo
let infoNSValue = info![UIKeyboardFrameBeginUserInfoKey] as! NSValue
let kbSize = infoNSValue.CGRectValue().size
let newHeight = kbSize.height
//backup old constraint size
myUITextViewBottomConstraintOld = myUITextViewBottomConstraint.constant
// I subtract 50 because otherwise it leaves a gap between keyboard and text view. I'm sure this could be improved on.
myUITextViewBottomConstraint.constant = newHeight - 50
func keyboardWillBeHidden(aNotification:NSNotification) {
//restore to whatever AutoLayout set it before you messed with it
myUITextViewBottomConstraint.constant = myUITextViewBottomConstraintOld
}
The code works, with a minor issue:
It's not responsive to the predictive text ribbon above the keyboard opening/closing. I.e. it will take the state of it into account when the keyboard is called up, but if you were to slide it up or down while keyboard is shown the constraint will not be adjusted. It is a separate event that needs to be handled. Its not enough of a functionality hit for me to bother with.
#Johnston found a good solution. Here's a variation using UIKeyboardWillChangeFrameNotification which correctly accounts for keyboard size changes (i.e. showing/hiding the QuickType bar). It also correctly handles the case where the text view is embedded in a navigation controller (i.e. where the contentInset isn't otherwise zero). It's also written in Swift 2.
override func viewDidLoad() {
:
NSNotificationCenter.defaultCenter().addObserverForName(UIKeyboardWillChangeFrameNotification, object: nil, queue: nil) { (notification) -> Void in
guard let userInfo = notification.userInfo,
let keyboardFrameEndValue = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue
else { return }
let windowCoordinatesKeyboardFrameEnd = keyboardFrameEndValue.CGRectValue() // window coordinates
let keyboardFrameEnd = self.view.convertRect(windowCoordinatesKeyboardFrameEnd, fromView: nil) // view coordinates
var inset = self.textView.contentInset
inset.bottom = CGRectGetMaxY(self.textView.frame) - CGRectGetMinY(keyboardFrameEnd) // bottom inset is the bottom of textView minus top of keyboard
self.textView.contentInset = inset
self.textView.scrollIndicatorInsets = inset
}
}

Custom UIProgressView drawing weirdness

I am trying to create my own custom UIProgressView by subclassing it and then overwrite the drawRect function.
Everything works as expected except the progress filling bar. I can't get the height and image right.
The images are both in Retina resolution and the Simulator is in Retina mode.
The images are called: "progressBar#2x.png" (28px high) and "progressBarTrack#2x.png" (32px high).
CustomProgressView.h
#import <UIKit/UIKit.h>
#interface CustomProgressView : UIProgressView
#end
CustomProgressView.m
#import "CustomProgressView.h"
#implementation CustomProgressView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, 16);
UIImage *progressBarTrack = [[UIImage imageNamed:#"progressBarTrack"] resizableImageWithCapInsets:UIEdgeInsetsZero];
UIImage *progressBar = [[UIImage imageNamed:#"progressBar"] resizableImageWithCapInsets:UIEdgeInsetsMake(4, 4, 5, 4)];
[progressBarTrack drawInRect:rect];
NSInteger maximumWidth = rect.size.width - 2;
NSInteger currentWidth = floor([self progress] * maximumWidth);
CGRect fillRect = CGRectMake(rect.origin.x + 1, rect.origin.y + 1, currentWidth, 14);
[progressBar drawInRect:fillRect];
}
#end
The resulting ProgressView has the right height and width. It also fills at the right percentage (currently set at 80%). But the progress fill image isn't drawn correctly.
Does anyone see where I go wrong?
Looks like you're reassigning self.frame in -drawRect.
I think you want something like this:
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
CGRect bounds = self.bounds ;
UIImage *progressBarTrack = [ UIImage imageNamed:#"progressBarTrack"] ;
[ progressBarTrack drawInRect:bounds ] ;
UIImage *progressBar = [[UIImage imageNamed:#"progressBar"] resizableImageWithCapInsets:(const UIEdgeInsets){ 4.0f, 4.0f, 5.0f, 4.0f } ] ;
CGRect fillRect = CGRectInset( bounds, 2.0f, 2.0f ) ;
fillRect.width = floorf( self.progress * maximumWidth );
[progressBar drawInRect:fillRect];
}
How to create your own progress view overriding UIView instead of UIProgressView
#interface ProgressView : UIView
#property float progress ;
#end
#implementation ProgressView
#synthesize progress = _progress ;
-(id)initWithFrame:(CGRect)frame
{
if (( self = [ super initWithFrame:frame ] ))
{
self.layer.needsDisplayOnBoundsChange = YES ;
}
return self ;
}
-(void)drawRect
{
// see code above
}
-(void)setProgress:(float)progress
{
_progress = progress ;
[ self setNeedsDisplay ] ;
}
#end

NSScrollView infinite / endless scroll | subview reuse

I'm searching for a way to implement something like reusable cells for UI/NSTableView but for NSScrollView. Basically I want the same like the WWDC 2011 video "Session 104 - Advanced Scroll View Techniques" but for Mac.
I have several problems realizing this. The first: NSScrollView doesn't have -layoutSubviews. I tried to use -adjustScroll instead but fail in setting a different contentOffset:
- (NSRect)adjustScroll:(NSRect)proposedVisibleRect {
if (proposedVisibleRect.origin.x > 600) {
// non of them work properly
// proposedVisibleRect.origin.x = 0;
// [self setBoundsOrigin:NSZeroPoint];
// [self setFrameOrigin:NSZeroPoint];
// [[parentScrollView contentView] scrollPoint:NSZeroPoint];
// [[parentScrollView contentView] setBoundsOrigin:NSZeroPoint];
}
return proposedVisibleRect;
}
The next thing I tried was to set a really huge content view with a width of millions of pixel (which actually works in comparison to iOS!) but now the question is, how to install a reuse-pool?
Is it better to move the subviews while scrolling to a new position or to remove all subviews and insert them again? and how and where should I do that?
As best I can tell, -adjustScroll: is not where you want to tap into the scrolling events because it doesn't get called universally. I think -reflectScrolledClipView: is probably a better hookup point.
I cooked up the following example that should hit the high points of one way to do a view-reusing scroll view. For simplicity, I set the dimensions of the scrollView's documentView to "huge", as you suggest, rather than trying to "fake up" the scrolling behavior to look infinite. Obviously drawing the constituent tile views for real is up to you. (In this example I created a dummy view that just fills itself with red with a blue outline to convince myself that everything was working.) It came out like this:
// For the header file
#interface SOReuseScrollView : NSScrollView
#end
// For the implementation file
#interface SOReuseScrollView () // Private
- (void)p_updateTiles;
#property (nonatomic, readonly, retain) NSMutableArray* p_reusableViews;
#end
// Just a small diagnosting view to convince myself that this works.
#interface SODiagnosticView : NSView
#end
#implementation SOReuseScrollView
#synthesize p_reusableViews = mReusableViews;
- (void)dealloc
{
[mReusableViews release];
[super dealloc];
}
- (NSMutableArray*)p_reusableViews
{
if (nil == mReusableViews)
{
mReusableViews = [[NSMutableArray alloc] init];
}
return mReusableViews;
}
- (void)reflectScrolledClipView:(NSClipView *)cView
{
[super reflectScrolledClipView: cView];
[self p_updateTiles];
}
- (void)p_updateTiles
{
// The size of a tile...
static const NSSize gGranuleSize = {250.0, 250.0};
NSMutableArray* reusableViews = self.p_reusableViews;
NSRect documentVisibleRect = self.documentVisibleRect;
// Determine the needed tiles for coverage
const CGFloat xMin = floor(NSMinX(documentVisibleRect) / gGranuleSize.width) * gGranuleSize.width;
const CGFloat xMax = xMin + (ceil((NSMaxX(documentVisibleRect) - xMin) / gGranuleSize.width) * gGranuleSize.width);
const CGFloat yMin = floor(NSMinY(documentVisibleRect) / gGranuleSize.height) * gGranuleSize.height;
const CGFloat yMax = ceil((NSMaxY(documentVisibleRect) - yMin) / gGranuleSize.height) * gGranuleSize.height;
// Figure out the tile frames we would need to get full coverage
NSMutableSet* neededTileFrames = [NSMutableSet set];
for (CGFloat x = xMin; x < xMax; x += gGranuleSize.width)
{
for (CGFloat y = yMin; y < yMax; y += gGranuleSize.height)
{
NSRect rect = NSMakeRect(x, y, gGranuleSize.width, gGranuleSize.height);
[neededTileFrames addObject: [NSValue valueWithRect: rect]];
}
}
// See if we already have subviews that cover these needed frames.
for (NSView* subview in [[[self.documentView subviews] copy] autorelease])
{
NSValue* frameRectVal = [NSValue valueWithRect: subview.frame];
// If we don't need this one any more...
if (![neededTileFrames containsObject: frameRectVal])
{
// Then recycle it...
[reusableViews addObject: subview];
[subview removeFromSuperview];
}
else
{
// Take this frame rect off the To-do list.
[neededTileFrames removeObject: frameRectVal];
}
}
// Add needed tiles from the to-do list
for (NSValue* neededFrame in neededTileFrames)
{
NSView* view = [[[reusableViews lastObject] retain] autorelease];
[reusableViews removeLastObject];
if (nil == view)
{
// Create one if we didnt find a reusable one.
view = [[[SODiagnosticView alloc] initWithFrame: NSZeroRect] autorelease];
NSLog(#"Created a view.");
}
else
{
NSLog(#"Reused a view.");
}
// Place it and install it.
view.frame = [neededFrame rectValue];
[view setNeedsDisplay: YES];
[self.documentView addSubview: view];
}
}
#end
#implementation SODiagnosticView
- (void)drawRect:(NSRect)dirtyRect
{
// Draw a red tile with a blue border.
[[NSColor blueColor] set];
NSRectFill(self.bounds);
[[NSColor redColor] setFill];
NSRectFill(NSInsetRect(self.bounds, 2,2));
}
#end
This worked pretty well as best I could tell. Again, drawing something meaningful in the reused views is where the real work is here.
Hope that helps.

How do I add views to an UIScrollView and keep it synchronized with a UIPageControl?

I need to dynamically create some views in my app and place some buttons on them dynamically again. If the amount (count) of the buttons is more then ten I want to place the buttons on a new view and the transitions between the views must be with UIPageControl. Even though I googled and searched from Apple's Developer page I couldn't find a way of solving my problem. Can someone please help?
Add your views as side-by-side subviews of an UIScrollView, using the addSubview method. Then use the UIPageControl with the UIScrollView, as in this example.
I made a class that manages a UIScrollView, a UIPageControl, and an array of UIViews. It is a simplified version of what I use in my own code. It does the following:
Sets up the scroll view to display an array of UIViews. It doesn't care if the views have been generated dynamically or not.
Handles scroll and page control events.
Synchronizes the scroll view with the page control.
PageViewManager.h
#import <Foundation/Foundation.h>
#interface PageViewManager : NSObject <UIScrollViewDelegate>
{
UIScrollView* scrollView_;
UIPageControl* pageControl_;
NSArray* pages_;
BOOL pageControlUsed_;
NSInteger pageIndex_;
}
- (id)initWithScrollView:(UIScrollView*)scrollView
pageControl:(UIPageControl*)pageControl;
- (void)loadPages:(NSArray*)pages;
- (void)loadControllerViews:(NSArray*)pageControllers;
#end
PageViewManager.m
#import "PageViewManager.h"
#interface PageViewManager ()
- (void)pageControlChanged;
#end
#implementation PageViewManager
- (id)initWithScrollView:(UIScrollView*)scrollView
pageControl:(UIPageControl*)pageControl
{
self = [super init];
if (self)
{
scrollView_ = scrollView;
pageControl_ = pageControl;
pageControlUsed_ = NO;
pageIndex_ = 0;
[pageControl_ addTarget:self action:#selector(pageControlChanged)
forControlEvents:UIControlEventValueChanged];
}
return self;
}
/* Setup the PageViewManager with an array of UIViews. */
- (void)loadPages:(NSArray*)pages
{
pages_ = pages;
scrollView_.delegate = self;
pageControl_.numberOfPages = [pages count];
CGFloat pageWidth = scrollView_.frame.size.width;
CGFloat pageHeight = scrollView_.frame.size.height;
scrollView_.pagingEnabled = YES;
scrollView_.contentSize = CGSizeMake(pageWidth*[pages_ count], pageHeight);
scrollView_.scrollsToTop = NO;
scrollView_.delaysContentTouches = NO;
[pages_ enumerateObjectsUsingBlock:^(id obj, NSUInteger index, BOOL *stop)
{
UIView* page = obj;
page.frame = CGRectMake(pageWidth * index, 0,
pageWidth, pageHeight);
[scrollView_ addSubview:page];
}];
}
/* Setup the PageViewManager with an array of UIViewControllers. */
- (void)loadControllerViews:(NSArray*)pageControllers
{
NSMutableArray* pages = [NSMutableArray arrayWithCapacity:
pageControllers.count];
[pageControllers enumerateObjectsUsingBlock:
^(id obj, NSUInteger idx, BOOL *stop)
{
UIViewController* controller = obj;
[pages addObject:controller.view];
}];
[self loadPages:pages];
}
- (void)pageControlChanged
{
pageIndex_ = pageControl_.currentPage;
// Set the boolean used when scrolls originate from the page control.
pageControlUsed_ = YES;
// Update the scroll view to the appropriate page
CGFloat pageWidth = scrollView_.frame.size.width;
CGFloat pageHeight = scrollView_.frame.size.height;
CGRect rect = CGRectMake(pageWidth * pageIndex_, 0, pageWidth, pageHeight);
[scrollView_ scrollRectToVisible:rect animated:YES];
}
- (void)scrollViewDidScroll:(UIScrollView*)sender
{
// If the scroll was initiated from the page control, do nothing.
if (!pageControlUsed_)
{
/* Switch the page control when more than 50% of the previous/next
page is visible. */
CGFloat pageWidth = scrollView_.frame.size.width;
CGFloat xOffset = scrollView_.contentOffset.x;
int index = floor((xOffset - pageWidth/2) / pageWidth) + 1;
if (index != pageIndex_)
{
pageIndex_ = index;
pageControl_.currentPage = index;
}
}
}
- (void)scrollViewWillBeginDragging:(UIScrollView*)scrollView
{
pageControlUsed_ = NO;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView*)scrollView
{
pageControlUsed_ = NO;
}
#end
To use this class, you embed it inside a UIViewController than contains the UIScrollView and the UIPageControl.
Usage:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// Create some views dynamically
UIView* v1 = ...
UIView* v2 = ...
// Put the views inside an NSArray:
NSArray* pages_ = [NSArray arrayWithObjects:v1, v2, nil];
/* Create the PageViewManager, which is a member (or property) of this
UIViewController. The UIScrollView and UIPageControl belong to this
UIViewController, but we're letting the PageViewManager manage them for us. */
pageViewManager_ = [[PageViewManager alloc]
initWithScrollView:self.scrollView
pageControl:self.pageControl];
// Make the PageViewManager display our array of UIViews on the UIScrollView.
[pageViewManager_ loadViews:pages_];
}
My sample code assumes that you're using ARC.