show animation when addsubview - animation

I want to add a subview with animation. I am using add sub view so it is not showing any animation so I want to show any animation when I am doing this... I am using below code :-
UIViewController *vControllerHome = [[viewTemp alloc] initWithNibName:#"viewTemp" bundle:nil];
vControllerHome.view.frame =CGRectMake(0, 0, 320, 414);
[self.view addSubview:vControllerHome.view];
self.selectedViewController = vControllerHome;
Can any one suggest how I do this?

Here's the code.. Just try it.
PS: Replace myView with the name of the view you want to replace.
CATransition *applicationLoadViewIn =[CATransition animation];
[applicationLoadViewIn setDuration:duration];
[applicationLoadViewIn setType:kCATransitionReveal];
[applicationLoadViewIn setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]];
[[myView layer]addAnimation:applicationLoadViewIn forKey:kCATransitionReveal];

here is for animation blocks
[UIView transitionWithView:containerView
duration:0.5
options:UIViewAnimationTransitionFlipFromRight //any animation
animations:^ { [containerView addSubview:subview]; }
completion:nil];

Maybe you can subclass the UIView and override method willMove(toSuperview newSuperview: UIView?)
Here is example:
override public func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
if let _ = newSuperview {
// This view will be added to some view
UIView.animate(withDuration: 0.2, delay: 0.0, usingSpringWithDamping: 0.6, initialSpringVelocity: 30.0, options: .curveEaseInOut, animations: {
//...
}, completion: { (finish) in
})
} else {
// This view will be removed
}
}

Related

Convert Obj-C to Swift

Trying to override drawPlaceholderInRect in Swift2.1 so that I change the text color and I am having a hard time converting the following Obj-C to Swift:
(void)drawPlaceholderInRect:(CGRect)rect
{
UIColor *colour = [UIColor whiteColor];
if ([self.placeholder respondsToSelector:#selector(drawInRect:withAttributes:)]) {
NSDictionary *attributes = #{NSForegroundColorAttributeName: colour, NSFontAttributeName: self.font};
CGRect boundingRect = [self.placeholder boundingRectWithSize:rect.size options:0 attributes:attributes context:nil];
[self.placeholder drawAtPoint:CGPointMake(0, (rect.size.height/2)-boundingRect.size.height/2) withAttributes:attributes];
}
I got this:
public override func drawPlaceholderInRect(rect: CGRect) {
let textDict: NSDictionary = [NSForegroundColorAttributeName: UIColor.whiteColor()]
...
..
.
}
Can someone help out please?
func drawPlaceholder(in rect: CGRect) {
let colour: UIColor? = UIColor.white
if placeholder.responds(to: Selector("drawInRect:withAttributes:")) {
let attributes = [NSForegroundColorAttributeName: colour, NSFontAttributeName: font]
let boundingRect: CGRect = placeholder.boundingRect(with: rect.size, options: [], attributes: attributes, context: nil)
placeholder.draw(at: CGPoint(x: 0, y: (rect.size.height / 2) - boundingRect.size.height / 2), withAttributes: attributes)
}
}
See if this is helpful:
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/index.html#//apple_ref/doc/uid/TP40014216-CH2-ID0
Also, if you have trouble translating Objective-C to Swift, which can be tricky sometimes, consider overriding the method in a derived Objective-C class and then using that class in Swift.

How to animate an object vertically with touch like Spotify's music player does when tapping the song,

Im using Xcode, and when i tap/drag on my imageView at the bottom of the screen, I want it to be brought up and reveal all of it on screen similiar to the way Spotify does it when you click the banner at the bottom. Any ideas?
I recommend using spring animations if you want a nice animation like this:
func buttonTapped(sender: UIButton!) { //or in an IBAction
let duration: NSTimeInterval = 0.75
let damping: CGFloat = 1
let velocity: CGFloat = 0.5
UIView.animateWithDuration(duration, delay: 0.5, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: .CurveLinear, animations: {
self.myView.center.y = self.view.frame.height/2
}, completion: nil)
}
Sorry for Swift code, if you're not able to translate it then let me know :)
Edit
For Objective-C the code would look something like this:
[UIView animateWithDuration:0.75, delay:0, usingSpringWithDamping:1, initialSpringVelocity:0.5, options:UIViewAnimationOptionsCurveLinear, animations:^{
//Animations
} completion:^(BOOL finished) {
//Completion Block
}];
I actually figured it out. I made a button and included this code to trigger the animation:
self.moveX.constant = 200;
[UIView animateWithDuration:2.0f animations:^{
imageView.frame = CGRectMake(0.0f, 200.0f, imageView.frame.size.width,imageView.frame.size.height);
}];

NSTextField Vertical alignment

I am creating cocoa app in which i created NSTextField programmatically like this,
NSView *superView = [[NSView alloc] initWithFrame:NSMakeRect(0, 300, 1400, 500)];
NSTextField *myTextField = [[NSTextField alloc] initWithFrame:NSMakeRect(180, 100, 1000, 300)];
[myTextField setStringValue:myText];
[myTextField setEditable:NO];
[myTextField setBezeled:NO];
[myTextField setDrawsBackground:NO];
[myTextField setSelectable:NO];
[myTextField setFont:[NSFont fontWithName:#"Futura" size:22]];
[superView addSubview:myTextField];
[superView setAutoresizesSubviews:YES];
[myTextField setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
[self.window.contentView addSubview:superView];
Now i want vertical alignment of my text and it should be adjustable according to text length.
Anyone have any suggestions? Please share your suggestion :)
Many Thanks..!!
What you want is possible, but you'll have to make a subclass of NSTextFieldCell, and then use that subclass in your NSTextField. The key methods you want override are drawingRectForBounds:, selectWithFrame:, and editWithFrame:
Here is a blog post from the fantastic Daniel Jalkut about this, he even includes a downloadable version ready to go. The post is fairly old but it should still work fine.
For adjusting the text field to string size you have to calculate the text size with NSString's sizeWithFont: constrainedToSize: lineBreakMode: before and than adjust the text field's size with setting the frame.
For vertical alignment look at this question (and the answers).
Here is a Swift version of the solution linked to by sosborn above:
open class VerticallyCenteredTextFieldCell: NSTextFieldCell {
fileprivate var isEditingOrSelecting : Bool = false
open override func drawingRect(forBounds rect: NSRect) -> NSRect {
let rect = super.drawingRect(forBounds: rect)
if !isEditingOrSelecting {
let size = cellSize(forBounds: rect)
return NSRect(x: rect.minX, y: rect.minY + (rect.height - size.height) / 2, width: rect.width, height: size.height)
}
return rect
}
open override func select(withFrame rect: NSRect, in controlView: NSView, editor textObj: NSText, delegate: Any?, start selStart: Int, length selLength: Int) {
let aRect = self.drawingRect(forBounds: rect)
isEditingOrSelecting = true
super.select(withFrame: aRect, in: controlView, editor: textObj, delegate: delegate, start: selStart, length: selLength)
isEditingOrSelecting = false
}
open override func edit(withFrame rect: NSRect, in controlView: NSView, editor textObj: NSText, delegate: Any?, event: NSEvent?) {
let aRect = self.drawingRect(forBounds: rect)
isEditingOrSelecting = true
super.edit(withFrame: aRect, in: controlView, editor: textObj, delegate: delegate, event: event)
isEditingOrSelecting = false
}
}
override ViewWillDraw and position your NSTextField in the center of its parent view at this point. This works with live resizing as well. You can also adjust font size at this point to find a font which fits the new size.

How to enable implicit animation in UIView when doing custom drawing?

I perform custom drawing in my UIView subclass using:
- (void)drawRect:(CGRect)rect;
How can I enable implicit animation when the drawing changes?
Since there were no other suggestions I went ahead with the layer delegate method. Perhaps that's the only option anyway.
So in MyView I created a new CALayer property:
-(CALayer*)stylesLayer
{
if (_stylesLayer == nil) {
CALayer *aLayer = [CALayer layer];
aLayer.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
if ([self respondsToSelector:#selector(setContentScaleFactor:)])
{
aLayer.contentsScale = self.contentScaleFactor;
}
_stylesLayer = aLayer;
[_stylesLayer retain];
[self.layer addSublayer:aLayer];
[aLayer release];
}
return _stylesLayer;
}
And in MyViewController I implemented the delegate method that does the drawing:
-(void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context
{
// custom drawing code here
}
Now when a certain property changes I update the layer from MyViewController, which implicitly does a cross fade animation.
-(void)setStyles:(NSArray *)styles
{
[styles retain];
[_styles release];
_styles = nil;
_styles = styles;
[self.myView.stylesLayer setNeedsDisplay];
}

How to fill the right bottom corner of NSScrollView?

I want to change its color, but I'm not sure wether to subclass NSScrollView or NSClipView. Or if the corner can be inserted as a regular NSView.
(source: flickr.com)
I don't need code. Just a hint at how to do it.
Already answered elsewhere on stackoverflow by mekentosj. The class to subclass is NSScrollView.
#interface MyScrollView : NSScrollView {
}
#end
#implementation MyScrollView
- (void)drawRect:(NSRect)rect{
[super drawRect: rect];
if([self hasVerticalScroller] && [self hasHorizontalScroller]){
NSRect vframe = [[self verticalScroller]frame];
NSRect hframe = [[self horizontalScroller]frame];
NSRect corner;
corner.origin.x = NSMaxX(hframe);
corner.origin.y = NSMinY(hframe);
corner.size.width = NSWidth(vframe);
corner.size.height = NSHeight(hframe);
// your custom drawing in the corner rect here
[[NSColor redColor] set];
NSRectFill(corner);
}
}
#end
Kind of odd but just subclassing NSScrollView and overriding draw with super.drawRect() made my NSScrollView (not) fill in that corner with white. I tested it 2x to make sure, since it doesn't make much sense.
import Cocoa
class ThemedScrollView: NSScrollView {
override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
}
}
Here's a Swift variation of the original answer as well:
import Cocoa
class ThemedScrollView: NSScrollView {
override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
if hasVerticalScroller && hasHorizontalScroller {
guard verticalScroller != nil && horizontalScroller != nil else { return }
let vFrame = verticalScroller!.frame
let hFrame = horizontalScroller!.frame
let square = NSRect(origin: CGPoint(x: hFrame.maxX, y: vFrame.maxY), size: CGSize(width: vFrame.width, height: hFrame.height))
let path = NSBezierPath(rect: square)
let fillColor = NSColor.redColor()
fillColor.set()
path.fill()
}
}
}
Updated Swift 5.2 version of Austin's answer
class Themed: NSScrollView {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
if hasVerticalScroller && hasHorizontalScroller {
guard verticalScroller != nil && horizontalScroller != nil else { return }
let vFrame = verticalScroller!.frame
let hFrame = horizontalScroller!.frame
let square = NSRect(origin: CGPoint(x: hFrame.maxX, y: vFrame.maxY), size: CGSize(width: vFrame.width, height: hFrame.height))
let path = NSBezierPath(rect: square)
let fillColor = NSColor.red
fillColor.set()
path.fill()
}
}
}

Resources