CSStickyHeaderFlowLayout swift - objective-c

I'm trying to make parallax photo effect in my app using CSStickyHeaderFlowLayout
- https://github.com/jamztang/CSStickyHeaderFlowLayout/
and Swift language.
I have installed necessary Pod's file, add #import "CSStickyHeaderFlowLayout.h" to my "appName"-Bridging-Header.h file, and implemented this method:
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
var cell: UICollectionViewCell = UICollectionViewCell(frame: CGRectMake(0, 0, 400, 200));
var imageView: UIImageView = UIImageView();
var image: UIImage = UIImage(named: "news2.jpg")!;
imageView.image = image;
cell.addSubview(imageView);
return cell;
}
but now I have difficulties to translate this Obj-C code to Swift:
CSStickyHeaderFlowLayout *layout = (id)self.collectionViewLayout;
if ([layout isKindOfClass:[CSStickyHeaderFlowLayout class]]) {
layout.parallaxHeaderReferenceSize = CGSizeMake(320, 200);
}
In my opinion after that step my effect should works. Am I right? Or I have missed something?
Thanks for help,
m.af

You should be able to do it like this in Swift
if let layout = self.collectionViewLayout as? CSStickyHeaderFlowLayout {
layout.parallaxHeaderReferenceSize = CGSizeMake(320, 200)
}

You could try this:
var layout = CSStickyHeaderFlowLayout()
if (layout.isKindOfClass(CSStickyHeaderFlowLayout.self)) {
layout.parallaxHeaderReferenceSize = CGSizeMake(self.view.frame.size.width, 426)
layout.parallaxHeaderMinimumReferenceSize = CGSizeMake(self.view.frame.size.width, 110)
layout.itemSize = CGSizeMake(self.view.frame.size.width, layout.itemSize.height)
layout.parallaxHeaderAlwaysOnTop = true
// If we want to disable the sticky header effect
layout.disableStickyHeaders = true
}

Related

How to use AVPlayer and Image in UITableViewCell depending upon the response from my API

Functionality : I need to implement a tableview where the cells will have either an image or a video depending upon the category in my API.
Whats happening : The images and video are displayed well but when a cell with video is displayed it replaces all the cell with AVPlayer, the cells with the images too.
Code : -
(in cellForRowAtIndexPath - )
if (![dict[#"video_360x290"] isEqualToString:#""]) {
AVPlayerItem* playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:dict[#"video_360x290"]]];
AVPlayer *playVideo = [[AVPlayer alloc] initWithPlayerItem:playerItem];
cell.playerViewController = [[AVPlayerViewController alloc] init];
cell.playerViewController.player = playVideo;
cell.playerViewController.player.volume = 10;
cell.playerViewController.view.frame = CGRectMake(0, 0, cell.vPost.frame.size.width, cell.vPost.frame.size.height);
[cell.vPost addSubview:cell.playerViewController.view];
[playVideo play];
}
else{
[cell.iPost sd_setImageWithURL:dict[#"image"] placeholderImage:[UIImage imageNamed:#"imageNotAvailable"] options:SDWebImageHighPriority];
}
What i Need : I need that cell with images displays images and cell with video displays video
Thanks in advance.
Let TableViewCell Class name is ImageVideoCell
Create THREE cells from Storyboard in TableView, 1 for Image and 2 for Video and change cell identifier. For Image Cell change Identifier to "ImageCell" and for Video Cell change Identifier to "VideoCell1" and "VideoCell2" add same tableViewCell Class on all cells like here ImageVideoCell.
And in Controller
class ViewController: UIViewController {
// MARK: - Outlets
#IBOutlet weak var tableView: UITableView!
// MARK: - Properties
var imgVideos = [ImgVideo?]()
var player : AVPlayer?
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
// API call to get Images and videos in TableView
tableView.dataSource = self
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(true)
if player?.isPlaying == true {
self.player?.pause()
self.player = nil
}
}
// MARK: - Action
#IBAction func play_pauseButtonPressed(_ sender: UIButton) {
guard let video = imgVideos[sender.tag] else { return } // get video URl here
guard let cell = tableView.cellForRow(at: IndexPath(row: sender.tag, section: 0)) as? ImageVideoCell else { return }
// if Video is already Playing And User want to Pause it then
if player?.isPlaying ?? false && video.isSelected {
player?.pause()
sender.setImage(#imageLiteral(resourceName: "play-button"), for: .normal)
}
// if the Video is pause and User want to Play it again
else if player?.isPlaying ?? true == false && video.isSelected {
player?.play()
sender.setImage(#imageLiteral(resourceName: "media-pause"), for: .normal)
}
// Play any other Video
else {
for (index, video) in audios.enumerated() {
if video?.isSelected ?? false {
video?.isSelected = false
tableView.beginUpdates()
tableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: .none)
tableView.endUpdates()
}
}
video.isSelected = true
tableView.beginUpdates()
tableView.reloadRows(at: [IndexPath(row: sender.tag, section: 0)], with: .none)
tableView.endUpdates()
guard let cell = tableView.cellForRow(at: IndexPath(row: sender.tag, section: 0)) as? ImageVideoCell else { return }
cell.play_pauseButton.setImage(#imageLiteral(resourceName: "media-pause"), for: .normal)
play(videoUrl: vedio.url ?? "") // Play is a function for playing Videos
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = ImageVideoCell()
if Image {
cell = tableView.dequeueReusableCell(withIdentifier: "ImageCell", for: indexPath) as! ImageVideoCell
// Display Img
}else {
if video?.isSelected ?? false {
cell = tableView.dequeueReusableCell(withIdentifier: "VideoCell1", for: indexPath) as! ImageVideoCell
}else {
cell = tableView.dequeueReusableCell(withIdentifier: "VideoCell2", for: indexPath) as! ImageVideoCell
}
}
cell.play_pauseButton.tag = indexPath.row
cell.play_pauseButton.setImage(audio?.isSelected ?? false ? #imageLiteral(resourceName: "media-pause") : #imageLiteral(resourceName: "play-button"), for: .normal)
return cell
}
}
// MARK: - AVPlayer
extension AVPlayer {
var isPlaying: Bool {
return ((rate != 0) && (error == nil))
}
}

How can I create a button with a background color for tvOS while still showing focus?

All I want to do is add a background color to a button for all states. But I want to maintain the automatic focus shadow that you get "for free" when using a system button in the tvOS storyboard. So far I haven't been able to find a combination that allows this.
Alternatively, I would also be interested in a way to programmatically add the shadow when the button is focused, but short of subclassing the button (which I haven't yet tried), I don't know how to do that either.
You can add a shadow for your custom button like this:
- (void)didUpdateFocusInContext:(UIFocusUpdateContext *)context withAnimationCoordinator:(UIFocusAnimationCoordinator *)coordinator
{
context.nextFocusedView.layer.shadowOffset = CGSizeMake(0, 10);
context.nextFocusedView.layer.shadowOpacity = 0.6;
context.nextFocusedView.layer.shadowRadius = 15;
context.nextFocusedView.layer.shadowColor = [UIColor blackColor].CGColor;
context.previouslyFocusedView.layer.shadowOpacity = 0;
}
Wasn't happy with a simple colour change, so I made a custom button subclass to look more like the default animation you get with system buttons -
class CustomButton: UIButton
{
private var initialBackgroundColour: UIColor!
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
initialBackgroundColour = backgroundColor
}
override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator)
{
coordinator.addCoordinatedAnimations(
{
if self.focused
{
self.backgroundColor = UIColor.whiteColor()
UIView.animateWithDuration(0.2, animations:
{
self.transform = CGAffineTransformMakeScale(1.1, 1.1)
},
completion:
{
finished in
UIView.animateWithDuration(0.2, animations:
{
self.transform = CGAffineTransformIdentity
},
completion: nil)
})
}
else
{
self.backgroundColor = self.initialBackgroundColour
}
},
completion: nil)
}
}
Nothing too complicated, but gets the job done
Override didUpdateFocusInContext method and check if next focus view is button, if yes then customize its UI, and to set it back to orignal state check context.previousFocusedView was that button, something like below
- (void)didUpdateFocusInContext:(UIFocusUpdateContext *)context withAnimationCoordinator:(UIFocusAnimationCoordinator *)coordinator
{
if (context.nextFocusedView == _button)
{
// set background color
}
else if (context.previousFocusedView == _button)
{
// set background color to background
}
}
The Ultimate Solution with inspiration from SomaMan. Just subclass all your custom buttons and you Get this:
includes: on tap animation and release and drag away.
//
// CustomFocusButton.swift
//
import UIKit
class CustomFocusButton: UIButton {
let focusedScaleFactor : CGFloat = 1.2
let focusedShadowRadius : CGFloat = 10
let focusedShadowOpacity : Float = 0.25
let shadowColor = UIColor.blackColor().CGColor
let shadowOffSetFocused = CGSizeMake(0, 27)
let animationDuration = 0.2
override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator)
{
coordinator.addCoordinatedAnimations({
if self.focused{
UIView.animateWithDuration(self.animationDuration, animations:{ [weak self] () -> Void in
guard let weakSelf = self else {return}
weakSelf.transform = CGAffineTransformMakeScale(weakSelf.focusedScaleFactor, weakSelf.focusedScaleFactor)
weakSelf.clipsToBounds = false
weakSelf.layer.shadowOpacity = weakSelf.focusedShadowOpacity
weakSelf.layer.shadowRadius = weakSelf.focusedShadowRadius
weakSelf.layer.shadowColor = weakSelf.shadowColor
weakSelf.layer.shadowOffset = weakSelf.shadowOffSetFocused
},completion:{ [weak self] finished in
guard let weakSelf = self else {return}
if !finished{
weakSelf.transform = CGAffineTransformMakeScale(weakSelf.focusedScaleFactor, weakSelf.focusedScaleFactor)
weakSelf.clipsToBounds = false
weakSelf.layer.shadowOpacity = weakSelf.focusedShadowOpacity
weakSelf.layer.shadowRadius = weakSelf.focusedShadowRadius
weakSelf.layer.shadowColor = weakSelf.shadowColor
weakSelf.layer.shadowOffset = weakSelf.shadowOffSetFocused
}
})
} else {
UIView.animateWithDuration(self.animationDuration, animations:{ [weak self] () -> Void in
guard let weakSelf = self else {return}
weakSelf.clipsToBounds = true
weakSelf.transform = CGAffineTransformIdentity
}, completion: {[weak self] finished in
guard let weakSelf = self else {return}
if !finished{
weakSelf.clipsToBounds = true
weakSelf.transform = CGAffineTransformIdentity
}
})
}
}, completion: nil)
}
override func pressesBegan(presses: Set<UIPress>, withEvent event: UIPressesEvent?) {
UIView.animateWithDuration(animationDuration, animations: { [weak self] () -> Void in
guard let weakSelf = self else {return}
weakSelf.transform = CGAffineTransformIdentity
weakSelf.layer.shadowOffset = CGSizeMake(0, 10);
})
}
override func pressesCancelled(presses: Set<UIPress>, withEvent event: UIPressesEvent?) {
if focused{
UIView.animateWithDuration(animationDuration, animations: { [weak self] () -> Void in
guard let weakSelf = self else {return}
weakSelf.transform = CGAffineTransformMakeScale(weakSelf.focusedScaleFactor, weakSelf.focusedScaleFactor)
weakSelf.layer.shadowOffset = weakSelf.shadowOffSetFocused
})
}
}
override func pressesEnded(presses: Set<UIPress>, withEvent event: UIPressesEvent?) {
if focused{
UIView.animateWithDuration(animationDuration, animations: {[weak self] () -> Void in
guard let weakSelf = self else {return}
weakSelf.transform = CGAffineTransformMakeScale(weakSelf.focusedScaleFactor, weakSelf.focusedScaleFactor)
weakSelf.layer.shadowOffset = weakSelf.shadowOffSetFocused
})
}
}
}
I've found something better:
-(void)didUpdateFocusInContext:(UIFocusUpdateContext *)context withAnimationCoordinator:(UIFocusAnimationCoordinator *)coordinator {
[coordinator addCoordinatedAnimations:^{
if (self.focused) {
self.backgroundColor = [UIColor whiteColor];
}
else {
self.backgroundColor = [UIColor clearColor];
}
} completion:nil];
}
Swift 4 /tvOS11 and better:
Set the ButtonType in the Interface Builder button properties to "Plain".
Add this private extension to your class:
private extension UIImage {
static func imageWithColor(color: UIColor, size: CGSize) -> UIImage? {
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(rect)
let image: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
Then in your connected IBOutlet set the background image for the focused state of the button:
#IBOutlet weak var myButton: UIButton! {
didSet {
let backgroundImageSelected = UIImage.imageWithColor(color: .red, size: myButton.bounds.size)
myButton.setBackgroundImage(backgroundImageSelected, for: .focused)
}
}
You can use the UIButton method setBackgroundImage(image: UIImage?, forState state: UIControlState) and pass through an image that is a flat color and the state .Normal.
This image can easily be created programatically from a UIColor and a size of 1x1:
func getImageWithColor(color: UIColor, size: CGSize) -> UIImage {
let rect = CGRectMake(0, 0, size.width, size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
You can set the background image in storyboard to an image that contains the color you would like

CALayer contents not being displayed in Swift2

import UIKit
class ViewController: UIViewController {
#IBOutlet weak var myView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "http://blogs.independent.co.uk/wp-content/uploads/2012/12/some-girls.jpg")
var image : UIImage? = nil
if let data = NSData(contentsOfURL: url!) {
image = UIImage(data: data)
}
let myLayer = CALayer()
myLayer.anchorPoint = CGPoint(x: 0, y: 0)
myLayer.bounds = CGRectMake(0, 0, self.view.bounds.width, self.view.bounds.height)
myLayer.position = CGPoint(x: 0,y: 0)
myLayer.borderColor = UIColor.redColor().CGColor
myLayer.borderWidth = 2.0
// the image is not displayed
myLayer.contents = image
print(myLayer.contents)
myView.layer.addSublayer(myLayer)
myView.layer.opacity = 0.3
}
}
The UIImage is not being displayed why is that? whats wrong with the code? Please Help anyone who is well versed in Core Animation and Swift
In CALayer CGImage is used and not UIImage Hence Convert the UIImage into CGImage like this :
myLayer.contents = image?.CGImage
This should fix that.

How to add QLPreviewController as Subview in objective C

Is it possible to add QLPreviewController to UIView as sub view.
I tried like this
[self.view addSubview:previewViewController.view]
I also called reloadData
[previewViewController reloadData];
I check with this URL Adding QLPreviewController as subview doesn't load PDF . But I did not understand what is self.pdfPreviewView
Please guide me how I can add QLPreviewController as sub view..
Yes its possible, see the code below:
QLPreviewController* preview = [[QLPreviewController alloc] init];
preview.dataSource = self;
preview.delegate = self;
[self addChildViewController:preview];//*view controller containment
//set the frame from the parent view
CGFloat w= self.quickLookView.frame.size.width;
CGFloat h= self.quickLookView.frame.size.height;
preview.view.frame = CGRectMake(0, 0,w, h);
[self.quickLookView addSubview:preview.view];
[preview didMoveToParentViewController:self];
//save a reference to the preview controller in an ivar
self.previewController = preview;
Swift 3.x
private var pVC: QLPreviewController?
override func viewDidLoad() {
super.viewDidLoad()
// I do not not why, but it needs to be setup after delay.
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: setupPreview)
}
private func setupPreview() {
if (pVC != nil) { return }
let preview = QLPreviewController()
preview.dataSource = self
preview.delegate = self
preview.view.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: previewView.frame.size)
previewView.addSubview(preview.view)
preview.didMove(toParentViewController: self)
pVC = preview
}

Best way to change the background color for an NSView

I'm looking for the best way to change the backgroundColor of an NSView. I'd also like to be able to set the appropriate alpha mask for the NSView. Something like:
myView.backgroundColor = [NSColor colorWithCalibratedRed:0.227f
green:0.251f
blue:0.337
alpha:0.8];
I notice that NSWindow has this method, and I'm not a big fan of the NSColorWheel, or NSImage background options, but if they are the best, willing to use.
Yeah, your own answer was right. You could also use Cocoa methods:
- (void)drawRect:(NSRect)dirtyRect {
// set any NSColor for filling, say white:
[[NSColor whiteColor] setFill];
NSRectFill(dirtyRect);
[super drawRect:dirtyRect];
}
In Swift:
class MyView: NSView {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// #1d161d
NSColor(red: 0x1d/255, green: 0x16/255, blue: 0x1d/255, alpha: 1).setFill()
dirtyRect.fill()
}
}
An easy, efficient solution is to configure the view to use a Core Animation layer as its backing store. Then you can use -[CALayer setBackgroundColor:] to set the background color of the layer.
- (void)awakeFromNib {
self.wantsLayer = YES; // NSView will create a CALayer automatically
}
- (BOOL)wantsUpdateLayer {
return YES; // Tells NSView to call `updateLayer` instead of `drawRect:`
}
- (void)updateLayer {
self.layer.backgroundColor = [NSColor colorWithCalibratedRed:0.227f
green:0.251f
blue:0.337
alpha:0.8].CGColor;
}
That’s it!
If you are a storyboard lover, here is a way that you don't need any line of code.
Add NSBox as a subview to NSView and adjust NSBox's frame as the same with NSView.
In Storyboard or XIB change Title position to None, Box type to Custom, Border Type to "None", and Border color to whatever you like.
Here is a screenshot:
This is the result:
If you setWantsLayer to YES first, you can directly manipulate the layer background.
[self.view setWantsLayer:YES];
[self.view.layer setBackgroundColor:[[NSColor whiteColor] CGColor]];
Think I figured out how to do it:
- (void)drawRect:(NSRect)dirtyRect {
// Fill in background Color
CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
CGContextSetRGBFillColor(context, 0.227,0.251,0.337,0.8);
CGContextFillRect(context, NSRectToCGRect(dirtyRect));
}
edit/update: Xcode 8.3.1 • Swift 3.1
extension NSView {
var backgroundColor: NSColor? {
get {
guard let color = layer?.backgroundColor else { return nil }
return NSColor(cgColor: color)
}
set {
wantsLayer = true
layer?.backgroundColor = newValue?.cgColor
}
}
}
usage:
let myView = NSView(frame: NSRect(x: 0, y: 0, width: 100, height: 100))
print(myView.backgroundColor ?? "none") // NSView's background hasn't been set yet = nil
myView.backgroundColor = .red // set NSView's background color to red color
print(myView.backgroundColor ?? "none")
view.addSubview(myView)
I went through all of these answers and none of them worked for me unfortunately. However, I found this extremely simple way, after about an hour of searching : )
myView.layer.backgroundColor = CGColorCreateGenericRGB(0, 0, 0, 0.9);
Best Solution :
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
self.wantsLayer = YES;
}
return self;
}
- (void)awakeFromNib
{
float r = (rand() % 255) / 255.0f;
float g = (rand() % 255) / 255.0f;
float b = (rand() % 255) / 255.0f;
if(self.layer)
{
CGColorRef color = CGColorCreateGenericRGB(r, g, b, 1.0f);
self.layer.backgroundColor = color;
CGColorRelease(color);
}
}
In Swift:
override func drawRect(dirtyRect: NSRect) {
NSColor.greenColor().setFill()
NSRectFill(dirtyRect)
super.drawRect(dirtyRect)
}
Use NSBox, which is a subclass of NSView, allowing us to easily style
Swift 3
let box = NSBox()
box.boxType = .custom
box.fillColor = NSColor.red
box.cornerRadius = 5
Without doubt the easiest way, also compatible with Color Set Assets:
Swift:
view.setValue(NSColor.white, forKey: "backgroundColor")
Objective-C:
[view setValue: NSColor.whiteColor forKey: "backgroundColor"];
Interface Builder:
Add a user defined attribute backgroundColor in the interface builder, of type NSColor.
Just set backgroundColor on the layer (after making the view layer backed).
view.wantsLayer = true
view.layer?.backgroundColor = CGColor.white
I tested the following and it worked for me (in Swift):
view.wantsLayer = true
view.layer?.backgroundColor = NSColor.blackColor().colorWithAlphaComponent(0.5).CGColor
In Swift 3, you can create an extension to do it:
extension NSView {
func setBackgroundColor(_ color: NSColor) {
wantsLayer = true
layer?.backgroundColor = color.cgColor
}
}
// how to use
btn.setBackgroundColor(NSColor.gray)
In swift you can subclass NSView and do this
class MyView:NSView {
required init?(coder: NSCoder) {
super.init(coder: coder);
self.wantsLayer = true;
self.layer?.backgroundColor = NSColor.redColor().CGColor;
}
}
This supports changing systemwide appearance (turning dark mode on or off) while the application is running. You can also set the background colour in Interface Builder, if you set the class of the view to BackgroundColorView first.
class BackgroundColorView: NSView {
#IBInspectable var backgroundColor: NSColor? {
didSet { needsDisplay = true }
}
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
wantsLayer = true
}
required init?(coder decoder: NSCoder) {
super.init(coder: decoder)
wantsLayer = true
}
override var wantsUpdateLayer: Bool { return true }
override func updateLayer() {
layer?.backgroundColor = backgroundColor?.cgColor
}
}
Have a look at RMSkinnedView. You can set the NSView's background color from within Interface Builder.
Just small reusable class (Swift 4.1)
class View: NSView {
var backgroundColor: NSColor?
convenience init() {
self.init(frame: NSRect())
}
override func draw(_ dirtyRect: NSRect) {
if let backgroundColor = backgroundColor {
backgroundColor.setFill()
dirtyRect.fill()
} else {
super.draw(dirtyRect)
}
}
}
// Usage
let view = View()
view.backgroundColor = .white