Can i use the class below by other ViewController's class by clicking dots at Page Controller? - ios11

There are 4 views:
DataViewController, GraphViewController and InfoViewController. PageViewController is made for switching between 3 others.
I've described everything to swipe my views by gestures. It works.
However, how can I use it in another view by clicking dots at "Page Control" object from any of 3 views?
import UIKit
class PageViewController: UIPageViewController
{
private(set) lazy var orderedViewControllers: [UIViewController] = {
return [self.ListedViewController(name: "Data"),
self.ListedViewController(name: "Graph"),
self.ListedViewController(name: "Info")]
}()
override func viewDidLoad()
{
super.viewDidLoad()
dataSource = self
if let firstViewController = orderedViewControllers.first {
setViewControllers([firstViewController],
direction: .forward,
animated: true,
completion: nil)
}
}
private func ListedViewController(name: String) -> UIViewController {
return UIStoryboard(name: "Main", bundle: nil) .
instantiateViewController(withIdentifier: "\(name)ViewController")
}
}
// MARK: UIPageViewControllerDataSource
extension PageViewController: UIPageViewControllerDataSource
{
func pageViewController(_ pageViewController: UIPageViewController,
viewControllerBefore viewController: UIViewController) -> UIViewController?
{
guard let viewControllerIndex = orderedViewControllers.index(of: viewController)
else
{
return nil
}
let previousIndex = viewControllerIndex - 1
// User is on the first view controller and swiped left to loop to
// the last view controller.
guard previousIndex >= 0
else
{
return orderedViewControllers.last
}
guard orderedViewControllers.count > previousIndex
else
{
return nil
}
return orderedViewControllers[previousIndex]
}
func pageViewController(_ pageViewController: UIPageViewController,
viewControllerAfter viewController: UIViewController) -> UIViewController?
{
guard let viewControllerIndex = orderedViewControllers.index(of: viewController)
else
{
return nil
}
let nextIndex = viewControllerIndex + 1
let orderedViewControllersCount = orderedViewControllers.count
// User is on the last view controller and swiped right to loop to
// the first view controller.
guard orderedViewControllersCount != nextIndex else
{
return orderedViewControllers.first
}
guard orderedViewControllersCount > nextIndex else
{
return nil
}
return orderedViewControllers[nextIndex]
}
func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
return orderedViewControllers.count
}
func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int {
guard let firstViewController = viewControllers?.first,
let firstViewControllerIndex = orderedViewControllers.index(of: firstViewController) else {
return 0
}
return firstViewControllerIndex
}
}
Should i implement the object
Page Control
by: sender: PageViewController?

First of all ad UIPageViewControllerDelegate and UIPageViewControllerData source to our class as follows:
import UIKit
class PageViewController: UIPageViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource {
Then we add the following function, this is used to load the view controllers as you scroll through the different views.
func newVc(viewController: String) -> UIViewController {
return UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: viewController)
}
Now above view did load add the following, the orderedViewControllers holds an array of View Controllers. If you want to add another View Controller to your page controller, this is the place to add it. We are adding in them by the storyboard identifiers sbBlue and sbRed we added earlier.
lazy var orderedViewControllers: [UIViewController] = {
return [self.newVc(viewController: "sbBlue"),
self.newVc(viewController: "sbRed")]
}()
(sbBlue and sbRed are identifiers in storyboard for each View)
Now add the following functions. These are used when your swiping through the page view controllers to load up the next view controller. This is configured so when you get to the last one, it will loop back to the start. If you swipe left on the first one it will load up the last one.
If you don’t want it to loop simply follow the instructions in the code to uncomment return nil and removing two lines of code. This is included in the code below.
// MARK: Data source functions.
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = orderedViewControllers.index(of: viewController) else {
return nil
}
let previousIndex = viewControllerIndex - 1
// User is on the first view controller and swiped left to loop to
// the last view controller.
guard previousIndex >= 0 else {
return orderedViewControllers.last
// Uncommment the line below, remove the line above if you don't want the page control to loop.
// return nil
}
guard orderedViewControllers.count > previousIndex else {
return nil
}
return orderedViewControllers[previousIndex]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = orderedViewControllers.index(of: viewController) else {
return nil
}
let nextIndex = viewControllerIndex + 1
let orderedViewControllersCount = orderedViewControllers.count
// User is on the last view controller and swiped right to loop to
// the first view controller.
guard orderedViewControllersCount != nextIndex else {
return orderedViewControllers.first
// Uncommment the line below, remove the line above if you don't want the page control to loop.
// return nil
}
guard orderedViewControllersCount > nextIndex else {
return nil
}
return orderedViewControllers[nextIndex]
}
Now in viewDidLoad() add the following:
self.dataSource = self
// This sets up the first view that will show up on our page control
if let firstViewController = orderedViewControllers.first {
setViewControllers([firstViewController],
direction: .forward,
animated: true,
completion: nil)
}
**
Adding the page dot indicators
**
To add the page dot indications add a pageControl as follows above the viewDidLoad()
var pageControl = UIPageControl()
Now add the following function. This will position the page control at the bottom of the screen. The current page indication will be black, and the rest of the indicators will be white. You can change these to suit the design of your app.
func configurePageControl() {
// The total number of pages that are available is based on how many available colors we have.
pageControl = UIPageControl(frame: CGRect(x: 0,y: UIScreen.main.bounds.maxY - 50,width: UIScreen.main.bounds.width,height: 50))
self.pageControl.numberOfPages = orderedViewControllers.count
self.pageControl.currentPage = 0
self.pageControl.tintColor = UIColor.black
self.pageControl.pageIndicatorTintColor = UIColor.white
self.pageControl.currentPageIndicatorTintColor = UIColor.black
self.view.addSubview(pageControl)
}
Now in viewDidLoad() add these two lines:
self.delegate = self
configurePageControl()
And add the following function, this will make sure the page control indicator changes to the correct page as you scroll through.
// MARK: Delegate functions
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
let pageContentViewController = pageViewController.viewControllers![0]
self.pageControl.currentPage = orderedViewControllers.index(of: pageContentViewController)!
}
Now run the app and you can see the page indicator as follows:

Related

Play swift sound based on each duration of I time in array

I want my swift code to call the playSound and play the sound based for the duration of each item in array playamount. So I want the user to play the sound for the first time for 10 seconds then play the sound starting at the beginning for 20 and then the same thing for 30 seconds. So the sound always starts at the beginning each time it is called.
import UIKit; import AVFoundation
class ViewController: UIViewController {
var player: AVAudioPlayer?
func playSound() {
let url = Bundle.mainBundle().URLForResource("rock", withExtension: "mp3")!
do {
player = try AVAudioPlayer(contentsOfURL: url)
guard let player = player else { return }
player.prepareToPlay()
player.play()
} catch let error as NSError {
print(error.description)
}
}
var playAmount : [Int] = [10,20,30]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
class ViewController: UIViewController {
var player: AVAudioPlayer?
var currentIndex: Int = 0
func runMusicBox() {
guard !playAmount.isEmpty else { return }
currentIndex = 0
newTimerForIndex(index: 0)
}
func newTimerForIndex(index: Int) {
player?.prepareToPlay()
player?.play()
Timer.scheduledTimer(withTimeInterval: Double(playAmount[index]), repeats: false) { timer in
self.player?.stop()
if self.currentIndex + 1 < self.playAmount.count {
self.currentIndex += 1
self.newTimerForIndex(index: self.currentIndex)
} else {
self.player?.stop()
}
}
}
func playSound() {
let url = Bundle.mainBundle().URLForResource("rock", withExtension: "mp3")!
do {
player = try AVAudioPlayer(contentsOfURL: url)
guard let player = player else { return }
runMusicBox()
} catch let error as NSError {
print(error.description)
}
}
var playAmount : [Int] = [10,20,30]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
Hi, can you try this code. Here I have a timer, and when one stops, then we check if we have another element in the array and will run a new timer. The Timer is working, but i didn;t check the player. if it works as expected - it should work for you

AVQueuePlayer won’t stop playing

If a person presses the button 10 times, then they will hear 10 different lists of songs being played continuously. I want it to be that if a person presses 10 times, they will only be listening to one list of songs. I'm basically trying to create a reset button.
var myQueuePlayer: AVQueuePlayer?
var avItems: [AVPlayerItem] = []
func audio () {
var items: [String] = ["one", "two", "three", "four", "five"]
items.shuffle()
for clip in items {
guard let url = Bundle.main.url(forResource: clip, withExtension: ".mp3") else {
// mp3 file not found in bundle - so crash!
fatalError("Could not load \(clip).mp3")
}
avItems.append(AVPlayerItem(url: url))
//button.isHidden = true
}
}
#IBAction func didTapButton() {
audio()
if myQueuePlayer == nil {
// instantiate the AVQueuePlayer with all avItems
myQueuePlayer = AVQueuePlayer(items: avItems)
} else {
// stop the player and remove all avItems
myQueuePlayer?.removeAllItems()
// add all avItems back to the player
avItems.forEach {
myQueuePlayer?.insert($0, after: nil)
}
}
// seek to .zero (in case we added items back in)
myQueuePlayer?.seek(to: .zero)
// start playing
myQueuePlayer?.play()
}
Here is a very simple example.
This assumes 5 .mp3 files in your bundle, and 4 buttons:
Play / Restart
Pause
Resume
Shuffle and Play
connected to the #IBAction funcs:
class TestAVQueuViewController: UIViewController {
var myQueuePlayer: AVQueuePlayer?
var avItemsArray: [AVPlayerItem] = []
override func viewDidLoad() {
super.viewDidLoad()
// assuming I have 5 .mp3 files in the bundle, named:
let mySongs: [String] = [
"clip1", "clip2", "clip3", "clip4", "clip5",
]
// build the array of URLs for the song files
for clip in mySongs {
if let url = Bundle.main.url(forResource: clip, withExtension: ".mp3") {
avItemsArray.append(AVPlayerItem(url: url))
} else {
print("Could not get URL for \(clip).mp3")
}
}
if avItemsArray.count == 0 {
fatalError("Failed to get URL for ANY songs!")
}
}
func playQueue() -> Void {
// if first time
if myQueuePlayer == nil {
// instantiate the AVQueuePlayer
myQueuePlayer = AVQueuePlayer()
}
guard let player = myQueuePlayer else {
// I suppose it's possible that AVQueuePlayer() failed to instantiate
// so print a message to debug console and return
print("AVQueuePlayer failed to instantiate!")
return
}
// this will make sure the player is stopped and remove any remaining avItems
player.removeAllItems()
// every time this is called,
// loop through and reset the time on each avItem
for item in avItemsArray {
item.seek(to: .zero, completionHandler: nil)
}
// add avItems to the player
avItemsArray.forEach {
player.insert($0, after: nil)
}
// start playing
player.play()
}
#IBAction func playRestartTapped(_ sender: Any) {
playQueue()
}
#IBAction func pauseTapped(_ sender: Any) {
guard let player = myQueuePlayer, player.items().count > 0 else {
return
}
player.pause()
}
#IBAction func resumeTapped(_ sender: Any) {
guard let player = myQueuePlayer, player.items().count > 0 else {
return
}
player.play()
}
#IBAction func restartShuffledTapped(_ sender: Any) {
// shuffle the items
avItemsArray.shuffle()
playQueue()
}
}

Google Places API request returns empty array but prints all responses - no error

I have the following error-free code and can't seem to use any of the information purposed for my results array. After playing around, I can print every businessID location listed but I can't add/use the array meant to hold this information. I do not understand why every location prints but my array appears as empty.
I apologize for the entirety of my code but I've spent hours trying to correct my issue...
import UIKit
import GooglePlaces
class FoodTwo: UITableViewController {
var placesClient: GMSPlacesClient!
let international: [String] = ["ChIJAQDABX7CIogRIEY3k6r7R-g",
"ChIJqX3q1IbCIogRFcuI05IPNDU",
"ChIJAQDABX7CIogRY2MA6XVas8E"]
let american: [String] = ["ChIJkX9tTSvoIogROXkxd0gpg3s", "ChIJy7lUZCfoIogRVBuB9jWKHUk", "ChIJyzCZMiroIogRkuMavnKsA0w", "ChIJbYvWJ5jCIogRxh0VQA_yD0I", "ChIJa4Sks23CIogRpRod4v5GEN8", "ChIJxVpGsNbpIogRG5HIAKbNyDU", "ChIJ1W32UyvoIogRyp_Rdxn6f8I", "ChIJwTht4ifoIogRsuXdEOrKGMk", "ChIJ6UXEgNPpIogR4Q3ZAAWQQSI", "ChIJUZVAjdTpIogRpyca26a6D8o", "ChIJ6-h6_EctIIgRO1kypozaGGs", "ChIJK8NGam7CIogRlzU1TKeSjVI", "ChIJ7Xxh1m3CIogRZ_yabslUzd8", "ChIJ_dxSGJ7CIogRcYwJhjAm7TQ"]
// more arrays here - deleted to reduce scrolling//
var results = [GMSPlace]()
var index: IndexPath!
override func viewDidLoad() {
super.viewDidLoad()
placesClient = GMSPlacesClient.shared()
var place: [String]
switch index.row
{
case 0 :
place = international
case 1 :
place = american
case 2 :
place = asian
case 3 :
place = bakery
case 4 :
place = bar
case 5 :
place = indian
case 6 :
place = italian
default :
place = mexican
}
for id in place
{
placesClient.lookUpPlaceID(id, callback: { (result, error) -> Void in
if let error = error {
print("lookup place id query error: \(error.localizedDescription)")
return
}
guard let result = result
else
{
print("No place details for \(id)")
return
}
self.results.append(result)
})
OperationQueue.main.addOperation( { () -> Void in
self.tableView.reloadData()
})
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return results.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FCT") as! FoodCellTwo
let each = results[indexPath.row]
cell.nameLabel.text = each.name
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
placesClient.lookUpPlaceID is an asynchronous function. You have to wait until it finishes. So, you are esentially reloading the table view before the array populates.
You should reload the table view after the array was filled.
for id in place {
placesClient.lookUpPlaceID(id) { result, error in
if let error = error {
print("lookup place id query error: \(error.localizedDescription)")
return
}
guard let result = result else {
print("No place details for \(id)")
return
}
self.results.append(result)
if place.count == self.results.count {
self.tableView.reloadData()
}
}
}

AVAudioPlayer using array to queue audio files - Swift

I am looking for a way to simply play audio files one after another.
AVAudioPlayer using an array seems to be the best solution. In fact, I was able to play the first element of the array using Sneak's recommendations found on this page : Here.
But I don't understand where and how to write the second call to AVAudioPlayer in order to play the second file?
The "audioPlayerDidFinishPlaying" function is not reacting. Why?
Thanks for watching.
import Cocoa
import AVFoundation
var action = AVAudioPlayer()
let path = Bundle.main.path(forResource: "test.aif", ofType:nil)!
let url = URL(fileURLWithPath: path)
let path2 = Bundle.main.path(forResource: "test2.aif", ofType:nil)!
let url2 = URL(fileURLWithPath: path2)
let array1 = NSMutableArray(array: [url, url2])
class ViewController: NSViewController
{
#IBOutlet weak var LanceStop: NSButton!
override func viewDidLoad()
{
super.viewDidLoad()
do
{
action = try AVAudioPlayer(contentsOf: array1[0] as! URL)
action.numberOfLoops = 0
action.prepareToPlay()
action.volume = 1
}catch{print("error")}
}
...
#IBAction func Lancer(_ sender: NSButton)
{
if action.isPlaying == true
{
action.stop()
action.currentTime = 0.0
LanceStop.title = "Lancer"
}
else
{
action.play()
LanceStop.title = "Stopper"
}
}
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool)
{
if flag == true
{
LanceStop.title = "Lancer"
}
}
}
But I don't understand where and how to write the second call to
AVAudioPlayer in order to play the second file?
So in order to play the second file, you need to write one method where you will need to initialize the audioplayer and invoke the same method inside audioplayer delegate method audioPlayerDidFinishPlaying like this:-
func playAudioFile(_ index: Int) {
do
{
action = try AVAudioPlayer(contentsOf: array1[index] as! URL)
action.numberOfLoops = 0
action.prepareToPlay()
action.volume = 1
} catch{print("error")
}
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
//This delegate method will called once it finished playing audio file.
//Here you can invoke your second file. You can declare counter variable
//and increment it based on your file and stop playing your file acordingly.
counter = counter + 1
playAudioFile(counter)
}
Note:- Set Audioplayer delegate to your ViewController in order to get invoke
audioPlayerDidFinishPlaying method like this.
action.delegate = self
Changed Code...
class ViewController: NSViewController, AVAudioPlayerDelegate
{
#IBOutlet weak var LanceStop: NSButton!
override func viewDidLoad()
{
super.viewDidLoad()
}
override var representedObject: Any?
{
didSet
{
// Update the view, if already loaded.
}
}
func playAudioFile(_ index: Int)
{
do
{
action = try AVAudioPlayer(contentsOf: array1[index] as! URL)
action.delegate = self
action.numberOfLoops = 0
action.prepareToPlay()
action.volume = 1
action.play()
}
catch{print("error")}
}
#IBAction func Lancer(_ sender: NSButton)
{
playAudioFile(0)
}
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool)
{
if flag == true
{
playAudioFile(1)
}
}
}

Pass an arrays row shown in an NSTableView to another array in Swift

I have 2 arrays
var messages = [Message]()
var screenMessages = [screenMessage]()
I have the messages array items in a NSTableView.. when I press an IBOutlet I would like to pass the items in that row to the screenMessages array to present in another NSTableView.
My NSTableView starts like so..
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
let result = tableView.makeViewWithIdentifier("cell", owner: self) as? secondviewTableCell
let mess = messages[row]
I've tried a number of ways of appending the screenMessages with the messages[row] but I can't put my finger on it. If anyone could demonstrate or point me in the right direction that would be brilliant.
Thank you.
Added more detail:
Screen one looks like so and when pressing the add button it should then pass that data from that row into screen twos tableview..
Screen two:
My View for screen one is as:
import Firebase
import Cocoa
var messages = [Message]()
var screenMessages = [screenMessage]()
class secondVC: NSViewController, NSTableViewDelegate, NSTableViewDataSource {
#IBOutlet weak var tableView: NSTableView!
#IBOutlet weak var screenRefreshBtn: NSButton!
#IBOutlet weak var refreshButton: NSButton!
var senderImageUrl: String!
var ref: Firebase!
var messagesRef: Firebase!
func setupFirebase() {
messagesRef = Firebase(url: "https://url.firebaseio.com/screenmessages")
messagesRef.queryLimitedToLast(25).observeEventType(FEventType.ChildAdded, withBlock: { (snapshot) in
let text = snapshot.value["text"] as? String
let sender = snapshot.value["senderName"] as? String
let imageUrl = snapshot.value["profileImageURL"] as? String
let MediaType = snapshot.value["MediaType"] as! String
let fileUrl = snapshot.value["fileUrl"] as? String
let message = Message(text: text, sender: sender, imageUrl: imageUrl, MediaType: MediaType, fileUrl: fileUrl)
messages.append(message)
let screenmessage = screenMessage(text: text, sender: sender, imageUrl: imageUrl, MediaType: MediaType, fileUrl: fileUrl)
screenMessages.append(screenmessage)
switch MediaType{
case "TEXT":
print("text message")
case "PHOTO":
print("photo message")
default:
print("default")
}
self.tableView.reloadData()
})
}
override func viewDidLoad() {
super.viewDidLoad()
setupFirebase()
}
// MARK: - Table View
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
return messages.count
}
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
let result = tableView.makeViewWithIdentifier("cell", owner: self) as? secondviewTableCell
let mess = messages[row]
if mess.text() == nil {
result?.textField?.alphaValue = 0
result!.sendertextView.stringValue = mess.sender()
let url = NSURL(string: mess.fileUrl()!)!
// Download task:
// - sharedSession = global NSURLCache, NSHTTPCookieStorage and NSURLCredentialStorage objects.
let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (responseData, responseUrl, error) -> Void in
// if responseData is not null...
if let data = responseData{
// execute in UI thread
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let photo = NSImage(data: data)!
result?.mediaPhoto.image = photo
})
}
}
task.resume()
} else {
result!.textField!.stringValue = mess.text()!
result!.sendertextView.stringValue = mess.sender()
}
return result
}
#IBAction func addtablerow(object: NSButton) {
let row = tableView.rowForView( object as NSView )
if ( row > -1 ) {
}
}
And my second screen is:
import Cocoa
class screenVC: NSViewController, NSTableViewDelegate, NSTableViewDataSource {
var addedObserver = false
#IBOutlet weak var tableView: NSTableView!
override func viewDidLoad() {
super.viewDidLoad()
refreshObs()
clearObs()
self.tableView.backgroundColor = NSColor.clearColor()
if let window = self.view.window {
// custom window here
window.level = Int(CGWindowLevelForKey(.FloatingWindowLevelKey))
} else {
addedObserver = true
self.addObserver(self, forKeyPath: "view.window", options: [.New, .Initial], context: nil)
}
}
func refreshList(notification: NSNotification){
self.tableView.alphaValue = 0
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
animateViewRefresh()
tableView.scrollToEndOfDocument(self)
}
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
return screenMessages.count
}
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
let result = tableView.makeViewWithIdentifier("cell2", owner: self) as? screenviewTableCell
let mess = screenMessages[row]
result?.senderLabel.stringValue = mess.sender()
if mess.text() != nil {
result?.messageTextView.stringValue = mess.text()!
let url = NSURL(string: mess.imageUrl()!)!
let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (responseData, responseUrl, error) -> Void in
if let data = responseData{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
result?.avatarImage.image = NSImage(data: data)
})
}}
task.resume()
} else {
result?.messageTextView.alphaValue = 0
let mess = screenMessages[row]
let url = NSURL(string: mess.fileUrl()!)!
let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (responseData, responseUrl, error) -> Void in
if let data = responseData{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let photo = NSImage(data: data)!
result?.mediaPhoto.image = photo
})
}
}
let url2 = NSURL(string: mess.imageUrl()!)!
let task2 = NSURLSession.sharedSession().dataTaskWithURL(url2) { (responseData, responseUrl, error) -> Void in
if let data = responseData{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
result?.avatarImage.image = NSImage(data: data)
})
}}
task.resume()
task2.resume()
}
return result
}
// MARK : Animate
func animateView(notification: NSNotification){
NSAnimationContext.runAnimationGroup({ (context) in
context.duration = 2
self.tableView.animator().alphaValue = 0
screenMessages.removeAll()
}, completionHandler: { () -> Void in
})}
func animateViewRefresh(){
NSAnimationContext.runAnimationGroup({ (context) in
context.duration = 4
self.tableView.animator().alphaValue = 1
}, completionHandler: { () -> Void in
})}
func refreshObs(){
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(screenVC.refreshList(_:)), name:"refreshMyTableView", object: nil)
}
func clearObs(){
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(screenVC.animateView(_:)), name:"clearMyTableView", object: nil)
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if let window = self.view.window {
// custom window here
window.level = Int(CGWindowLevelForKey(.FloatingWindowLevelKey))
window.titlebarAppearsTransparent = true
window.movableByWindowBackground = true
window.opaque = true
window.backgroundColor = NSColor.clearColor()
}
}
deinit {
if addedObserver {
self.removeObserver(self, forKeyPath: "view.window")
}
}
}
I have tried a number of things such as 'screenMessages += messages(row)' and appending to add that row to the screenMessages array but I've had no luck.
Am I going about this in the right way or is there a better way of doing so?
Thank you.
To append an element from one array to another array just write
let index = index of element you need
let message = messages[index]
screenMessages.append(message)
If message is not the same type as the contents of the screenMessages array you will need to convert it, I would need more details of the types to help with that.
If you are having trouble passing the data to another ViewController I would need more information on the current architecture to give good advice, but for example you might define a protocol MessageDelegate that one of the controllers implements and the other has as a property.
update
If you update your data array for a table and want the new information to appear remember to call reloadData on the UITableView

Resources