I have a UIViewController - WSProfileViewController. This VC has a headerView, and then a containerView that loads one of three tableViewController as a childViewController of WSProfileViewController. I want to be able to scroll the headerView up whenever the current tableView scrolls up, as if it was a headerView of the tableView itself.
In the main VC, WSProfileViewController, I made it a UIScrollViewDelegate and implemented scrollViewDidScroll, but it's never called. It currently has no connection the the scrollViews of the child tableViews.
*Each child tableViewController has different data models, and are classes used elsewhere, so I want to keep them as is and just load them as children.
So I didn't want to alter any of the code for the child view controllers but I'm pretty sure there isn't any way for the parent to directly capture child scrolling unless I make it the delegate of the child tableviews, but I can't do that because each child view controller needs to be their own tableview's delegate.
Correct me if I'm missing something.
What I did was send a notification from each child's scrollViewDidScroll method like so:
#pragma mark - UIScrollView Delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
NSDictionary *scrollViewInfo = [NSDictionary dictionaryWithObject:scrollView forKey:#"someKey"];
[[NSNotificationCenter defaultCenter] postNotificationName:#"someNotificationName" object:nil userInfo:scrollViewInfo];
}
And then simply observe that in the parent:
#pragma mark - Notifications
- (void)registerForNotifications {
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(childScrollViewDidScroll:) name:#"someNotificationName" object:nil];
}
- (void)childScrollViewDidScroll:(NSNotification *)note {
UIScrollView* scrollView = [[note userInfo] valueForKey:#"someKey"];
CGFloat scrollOffset = scrollView.contentOffset.y;
CGRect headerFrame = self.headerView.frame;
headerFrame.origin.y = -scrollOffset;
self.headerView.frame = headerFrame;
}
It's scrolling the header view on the device without lag, so at least for the moment I'm satisfied.
Related
After switching to iOS8, I'm getting weird behavior when I move views during a keyboard transition. Can anyone explain what's going on?
Here's a minimal example to demonstrate the problem. I have a simple view with a UITextField and a UIButton. The function nudgeUp moves the text field and the button up by 10 points. It is triggered either by the buttonPressed callback, or the keyboardWillShow callback.
When I tap the button, the code works as expected: buttonPressed calls nudgeUp and the button and text field jump up by 10 points.
When I tap the text field, keyboardWillShow calls nudgeUp, but the behaviour is very different. The button and text field immediately jump down by 10 points, and then slide back up to their original position as the keyboard shows itself.
Why is this happening? How can I regain control of animations during keyboard presentation in iOS8?
#import "ViewController.h"
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
}
- (void)keyboardWillShow:(NSNotification *)notification
{
// Called when the keyboard appears.
[self nudgeUp];
}
- (IBAction)buttonPressed:(id)sender {
[self nudgeUp];
}
- (void)nudgeUp
{
CGRect newTextFieldFrame = self.textField.frame;
newTextFieldFrame.origin.y -= 10;
self.textField.frame = newTextFieldFrame;
CGRect newButtonFrame = self.button.frame;
newButtonFrame.origin.y -= 10;
self.button.frame = newButtonFrame;
}
#end
It's AutoLayout. Something changed in iOS8 and you can't just change frame or center points anymore if you have AutoLayout enabled. You have to create an outlet(s) of your constraint (vertical space) and update it accordingly instead of changing frame position. Constraints are like any other ui control and can have an outlet. Constraint change can be animated.
Example:
[UIView animateWithDuration:[notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue] delay:0 options:[[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue] animations:^{
self.bottomSpaceConstraint.constant = adjustmentedValue;
[self.view layoutIfNeeded];
} completion:^(BOOL finished) {
}];
You should use UIKeyboardDidShowNotification (you're using will version) and everything will work as you expect:
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardDidShow:)
name:UIKeyboardDidShowNotification
object:nil];
}
- (void)keyboardDidShow:(NSNotification *)notification
{
// Called when the keyboard finished showing up
[self nudgeUp];
}
The explanation is that with UIKeyboardWillShowNotification you are changing the frames too early. After your changes the system will relayout everything to accomodate the keyboard and your changes won't have any effect.
Also, I recommend you to switch to autolayout and forget about frames.
Try using the UIKeyboardWillShowNotification userInfo to give you the frame of the keyboard. Then move the onscreen elements based on that.
I have been working on this for hours, have no idea what went wrong. I want a custom cursor for a button which is a subview of NSTextView, I add a tracking area and send the cursorUpdate message when mouse entered button.
The cursorUpdate method is indeed called every time the mouse entered the tracking area. But the cursor stays the IBeamCursor.
Any ideas?
Reference of the Apple Docs: managing cursor-update event
- (void)cursorUpdate:(NSEvent *)event {
[[NSCursor arrowCursor] set];
}
- (void)myAddTrackingArea {
[self myRemoveTrackingArea];
NSTrackingAreaOptions trackingOptions = NSTrackingCursorUpdate | NSTrackingMouseEnteredAndExited | NSTrackingActiveInKeyWindow;
_trackingArea = [[NSTrackingArea alloc] initWithRect: [self bounds] options: trackingOptions owner: self userInfo: nil];
[self addTrackingArea: _trackingArea];
}
- (void)myRemoveTrackingArea {
if (_trackingArea)
{
[self removeTrackingArea: _trackingArea];
_trackingArea = nil;
}
}
I ran into the same problem.
The issue is, that NSTextView updates its cursor every time it receives a mouseMoved: event. The event is triggered by a self updating NSTrackingArea of the NSTextView, which always tracks the visible part of the NSTextView inside the NSScrollView. So there are maybe 2 solutions I can think of.
Override updateTrackingAreas remove the tracking area that is provided by Cocoa and make sure you always create a new one instead that excludes the button. (I would not do this!)
Override mouseMoved: and make sure it doesn't call super when the cursor is over the button.
- (void)mouseMoved:(NSEvent *)theEvent {
NSPoint windowPt = [theEvent locationInWindow];
NSPoint superViewPt = [[self superview]
convertPoint: windowPt fromView: nil];
if ([self hitTest: superViewPt] == self) {
[super mouseMoved:theEvent];
}
}
I had the same issue but using a simple NSView subclass that was a child of the window's contentView and did not reside within an NScrollView.
The documentation for the cursorUpdate flag of NSTrackingArea makes it sound like you only need to handle the mouse entering the tracking area rect. However, I had to manually check the mouse location as the cursorUpdate(event:) method is called both when the mouse enters the tracking area's rect and when it leaves the tracking rect. So if the cursorUpdate(event:) implementation only sets the cursor without checking whether it lies within the tracking area rect, it is set both when it enters and leaves the rect.
The documentation for cursorUpdate(event:) states:
Override this method to set the cursor image. The default
implementation uses cursor rectangles, if cursor rectangles are
currently valid. If they are not, it calls super to send the message
up the responder chain.
If the responder implements this method, but decides not to handle a
particular event, it should invoke the superclass implementation of
this method.
override func cursorUpdate(with event: NSEvent) {
// Convert mouse location to the view coordinates
let mouseLocation = convert(event.locationInWindow, from: nil)
// Check if the mouse location lies within the rect being tracked
if trackingRect.contains(mouseLocation) {
// Set the custom cursor
NSCursor.openHand.set()
} else {
// Reset the cursor
super.cursorUpdate(with: event)
}
}
I just ran across this through a Google search, so I thought I'd post my solution.
Subclass the NSTextView/NSTextField.
Follow the steps in the docs to create an NSTrackingArea. Should look something like the following. Put this code in the subclass's init method (also add the updateTrackingAreas method):
NSTrackingArea *trackingArea = [[NSTrackingArea alloc] initWithRect:self.bounds options:(NSTrackingMouseMoved | NSTrackingActiveInKeyWindow) owner:self userInfo:nil];
[self addTrackingArea:trackingArea];
self.trackingArea = trackingArea;
Now you need to add the mouseMoved: method to the subclass:
- (void)mouseMoved:(NSEvent *)theEvent {
NSPoint point = [self convertPoint:theEvent.locationInWindow fromView:nil];
if (NSPointInRect(point, self.popUpButton.frame)) {
[[NSCursor arrowCursor] set];
} else {
[[NSCursor IBeamCursor] set];
}
}
Note: the self.popUpButton is the button that is a subview of the NSTextView/NSTextField.
That's it! Not too hard it ends up--just had to used mouseMoved: instead of cursorUpdate:. Took me a few hours to figure this out, hopefully someone can use it.
I am developing my first MAC application, i downloaded one Example of PxListView
and i have to added one button and background image on cell xib and bind them with controller
and, when on button click i was set height of that cell is much bigger then other. that is done,
and work fine.
but now i want to develop like after is witch cell has open in that cell i want to add some extra contain (Controller) on it, so how it will possible using given example?
pls help me to give some suggest how it will be done.
for Ex like before click on button
after chick on button i want to develop like
You write
i have to added one button and background image on cell xib and bind them with controller
It sounds like you've subclassed PXListViewCell--for convenience, let's call your subclass TemplateListViewCell--and added a xib from which instances of TemplateListViewCell will be loaded in
+[PXListViewCell cellLoadedFromNibNamed:bundle:reusableIdentifier:]
In addition, there is a[t least one] button in TemplateListViewCell.xib.
You write
when on button click i was set height of that cell is much bigger then other. that is done, and work fine
It sounds like this button has as its action a method on TemplateListViewCell such as
- (IBAction)toggleDetail:(id)sender
{
//Code to grow or shrink the height of [self frame].
//...
}
In my approach to implementing -toggleDetail, two modifications to the PXListView files were necessary:
1. Adding a protocol method
- (void)listView:(PXListView *)aListView setHeight:(CGFloat)height ofRow:(NSUInteger)row;
to the PXListViewDelegate protocol.
2. Adding a property
#property (nonatomic, assign) BOOL expanded;
to PXListViewCell.
My implementation of -toggleDetail looks something like this:
- (IBAction)toggleDetail:(id)sender
{
BOOL wasExpanded = [self expanded];
NSRect oldFrame = [self frame];
CGFloat oldHeight = oldFrame.size.height;
CGFloat newHeight = oldHeight;
CGFloat heightIncrement = 0.0f;
if (wasExpanded) {
heightIncrement = -80.0f; //use whatever value is appropriate
} else {
heightIncrement = 80.0f; //use whatever value is appropriate
}
newHeight += heightIncrement;
[[[self listView] delegate] listView:[self listView] setHeight:newHeight ofRow:[self row]];
[[self listView] reloadData];
BOOL isExpanded = !wasExpanded;
[self setExpanded:isExpanded];
}
It might seem better to use [[self listView] reloadRowAtIndex:[self row]]; in place of [[self listView] reloadData], but unfortunately, this doesn't work: if the user hides the detail--shrinks the cell vertically--new cells which should appear on the screen do not.
You write
that is done, and work fine.
It sounds like you were able to implement successfully a method analogous to -[TemplateListViewCell toggleDetail:].
You write
but now i want to develop like after is witch cell has open in that cell i want to add some extra contain (Controller) on it, so how it will possible using given example? pls help me to give some suggest how it will be done.
It sounds like you want instances of TemplateListViewCell to contain extra views if they are expanded.
It might seem tempting to put this code into -[TemplateListViewCell toggleDetail], but this will not work out as we might hope. The trouble is, we need to handle cases where expanded cells have been scrolled out of view and scrolled back into view.
To get this right, we need to have a notion of expanded which persists beyond the usage of a PXListViewCell subclass instance: we either need to keep track of expansion in the PXListView itself or in its delegate.
The better--but less expedient--design seems to be to keep track of this information in the PXListView itself. For the sake of this question, however, I'll demonstrate how to keep track of cell expansion in the delegate. To do this, I'm expanding the PXListViewDelegate protocol and making other changes to the PXListView files:
1. Adding the methods
- (void)listView:(PXListView *)aListView setExpanded:(BOOL)expanded atRow:(NSUInteger)row;
- (BOOL)listView:(PXListView *)aListView expandedAtRow:(NSUInteger)row;
to PXListViewDelegate.
2. Adding the method
- (void)setCell:(PXListViewCell *)cell expandedAtRow:(NSUInteger)row
{
if ([[self delegate] respondsToSelector:#selector(listView:expandedAtRow:)]) {
[cell setExpanded:[[self delegate] listView:self expandedAtRow:row]];
}
}
to PXListView.
3. Calling -[PXListView setCell:expandedAtRow:] from -[PXListView layoutCells]
- (void)layoutCells
{
//Set the frames of the cells
for(id cell in _visibleCells)
{
NSInteger row = [cell row];
[cell setFrame:[self rectOfRow:row]];
[self setCell:cell expandedAtRow:row];
[cell layoutSubviews];
}
NSRect bounds = [self bounds];
CGFloat documentHeight = _totalHeight>NSHeight(bounds)?_totalHeight:(NSHeight(bounds) -2);
//Set the new height of the document view
[[self documentView] setFrame:NSMakeRect(0.0f, 0.0f, NSWidth([self contentViewRect]), documentHeight)];
}
and from -[PXListView layoutCell:atRow:]:
- (void)layoutCell:(PXListViewCell*)cell atRow:(NSUInteger)row
{
[[self documentView] addSubview:cell];
[cell setFrame:[self rectOfRow:row]];
[cell setListView:self];
[cell setRow:row];
[cell setHidden:NO];
[self setCell:cell expandedAtRow:row];
}
4. Setting _expanded to NO in -[PXListViewCell prepareForReuse]:
- (void)prepareForReuse
{
_dropHighlight = PXListViewDropNowhere;
_expanded = NO;
}
Note: In the sample PXListViewCell subclass, MyListViewCell, distributed with PXListView, the implementation of -[MyListViewCell prepareForReuse] fails to call [super prepareForReuse]. Make sure that this call is made in [TemplateListViewCell prepareForReuse]:
- (void)prepareForReuse
{
//...
[super prepareForReuse];
}
One change needs to be made to -[TemplateListViewCell toggleDetail:]. The line
[self setExpanded:isExpanded];
needs to be replaced by
[[[self listView] delegate] listView:[self listView] setExpanded:isExpanded atRow:[self row]];
Once you've set up your PXListView's delegate to properly handle the new delegate methods, you're ready to override [PXListViewCell setExpanded:] in your subclass TemplateListViewCell:
- (void)setExpanded:(BOOL)expanded
{
if (expanded) {
//add detail subviews
} else {
//remove detail subviews
}
[super setExpanded:expanded];
}
Replace //add detail subviews with your own code which programmatically adds the detail subviews that you want and replace //remove detail subviews with code to remove the detail subviews that you want, checking to see that they are present first.
You write
i want to add some extra contain (Controller) on it
It sounds like you want to add view controllers rather than views to your TemplateListViewCell. To do this, use an NSBox and set the box's contentView to your view controller's view. (For details on this, see this answer.)
If you plan on just showing a single view controller's view in an NSBox on the expanded TemplateListViewCell, you can just (1) add a property to TemplateListViewCell referencing your view controller and (2) add an NSBox to TemplateListViewCell xib and set its contentView to the appropriate view controller's view on [cell setExpanded:YES] and set its contentView to nil on [cell setExpanded:NO].
I know how to handle push segues in Storyboard and the use of the back button that is created with the navigation controller. I have one main tableview connected to a child tableview via push segue in Storyboard. Works fine for switching between tables.
I want to add the ability to also gesture swipe left in the child tableview to return to main tableview.
First tried this within Storyboard with the use of the swipe gesture recognizer, but this caused the main tableview to become a new child to the child tableview.
I then tried within code:
[self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
... but this seems to only work with a modal segue
I have:
- (void)viewDidLoad
{
[super viewDidLoad];
UISwipeGestureRecognizer *recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(handleSwipe:)];
[recognizer setDirection:(UISwipeGestureRecognizerDirectionLeft)];
[self.tableView addGestureRecognizer:recognizer];
}
- (void)handleSwipe:(UISwipeGestureRecognizer *)gestureRecognizer
{
// need code here to dismiss the child tableview
}
Finally figured it out today and it works perfectly:
- (void)handleSwipe:(UISwipeGestureRecognizer *)gestureRecognizer
{
[self.navigationController popViewControllerAnimated:YES];
}
Found answer in:
iOS Developer Library > UINavigationController Class Reference > popToViewController
I cannot figure out how to have a WebView in Objective-c detect when a scroll has been made. I have looked at the WebFrameLoadDelegate: and found didChangeLocationWithinPageForFrame: method, but that did seem to work.
You'll want to detect the webview is scrolling by using javascript. If you do a quick google search on "uiwebview javascript" you'll see plenty of examples on how to have javascript run in the uiwebivew. Once you get the javascript to detect the scroll occurring then you have the javascript change window.location to something fake and implement the "webView:shouldStartLoadWithRequest:navigationType:" delegate to execute objective-c code. Return NO from the delegate method to not load the request.
Depends on whether you are using a UIWebView (iOS - Cocoa Touch) or WebView (OS X - Cocoa).
iOS (iOS 5 and later):
UIWebView exposes its UIScrollView, and you can set the scroll view's delegate and then implement the delegate scrollViewDidScroll: delegate method (adding to your class's #interface declaration first, of course; this example is in a UIViewController subclass):
- (void)viewDidLoad {
[super viewDidLoad];
[_webView.scrollView setDelegate:self];
}
#pragma mark UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
// do something in response to scroll
}
}
OS X:
Add an observer for the NSViewBoundsDidChangeNotification of the WebView (this example is in an NSWindowController subclass):
- (id)initWithWindowNibName:(NSString *)windowNibName {
self = [super initWithWindowNibName:windowNibName];
if (self) {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(_scrollDetected)
name:NSViewBoundsDidChangeNotification
object:_webView];
}
return self;
}
- (void)_scrollDetected {
// do something in response to scroll
}
On OS X, you can detect it by subscribing to NSScrollViewWillStartLiveScrollNotification:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(mySelector:)
name:NSScrollViewWillStartLiveScrollNotification object:nil];
I pass nil as the object parameter because when I get it, it doesn't appear to actually come from the enclosingScrollView on the WebView. And there is no scroll view property on WKWebView in Yosemite. So when handling it, you have to check if it's your web view sending it (being paranoid about type safety):
-(void)handleScroll:(id)sender
{
if ([sender isKindOfClass:[NSNotification class]])
{
NSNotification *notif = (NSNotification *)sender;
if ([notif.object isKindOfClass:[NSView class]])
{
NSView *view = (NSView *)notif.object;
if ([view isDescendantOf:self.webView])
{
//Handle scroll here
}
}
}
}
I have only tried this descendent-checking thing with WebView, so if you're using WKWebView, YMMV.
There are other scroll notifications listed in the NSScrollView documentation.