dimanche 28 juin 2015

UILabel doesn't update immediately after setting value in NSUserDefaults

I have two view controllers, of which one is for entering a value that is stored in NSUserDefaults, the other one contains a label that shows this value. The value is NOT shown immediately after setting the value in the first view controller, but it gets stored in NSUserDefaults. If I open the view controller again via my sidebar, the value is shown. I need the view to update immediately.

This is the code of my first view controller:

import UIKit

class profileSettings: UIViewController {

@IBOutlet weak var vornameLabel: UITextField!
@IBOutlet weak var nachnameLabel: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}


@IBAction func saveInformation(sender: AnyObject) {

    NSUserDefaults().setObject(vornameLabel.text, forKey: "vorname")
    NSUserDefaults().setObject(nachnameLabel.text, forKey: "nachname")

}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    //in Profil
    var destProfile:profile = segue.destinationViewController as! profile

    destProfile.vornameLabel = vornameLabel.text
    destProfile.nachnameLabel = nachnameLabel.text

} 
}

This is the code for my second view controller:

import UIKit

var vorname = ""
var nachname = ""

class profile: UIViewController, SideBarDelegate {

var sideBar:SideBar = SideBar()

var vornameLabel = String()
var nachnameLabel = String()

//Name
@IBOutlet weak var nameTextField: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    // SideBar
    sideBar = SideBar(sourceView: self.view, menuItems: ["1", "2", "3", "4", "5"])
    sideBar.delegate = self

    //Name anzeigen
    vorname = NSUserDefaults().stringForKey("vorname") ?? ""
    NSUserDefaults.standardUserDefaults().setObject(vorname, forKey: "vorname")

    nachname = NSUserDefaults().stringForKey("nachname") ?? ""
    NSUserDefaults.standardUserDefaults().setObject(nachname, forKey: "nachname")

    //Name
    nameTextField.text = vorname + " " + nachname

}

Can't center UIScrollView around CGPoint on y axis, or when zoomed

I am trying to center a CGPoint inside the Visible Rectangle that is my UIScrollView.

Here is the setup:

enter image description here

I have a SpriteKit scene with some objects on it. This scene is basically the View for my UIScrollView. The Scene is much larger than the visible scene on the device, as show with the visible rectangle.

I want to set the contentOffset of the UIScrollView so that a point is in the center of the visible rect.

enter image description here

Here is what I have tried doing, to no avail:

    CGPoint adjustment = CGPointMake(visibleRect.size.width/2, visibleRect.size.height/2);
    CGPoint wantedMidPoint = node.position;

    CGPoint newOffset = CGPointMake(wantedMidPoint.x - adjustment.x, wantedMidPoint.y + adjustment.y);

The Offset is then set as follows:

[self.scrollView setContentOffset:newOffset animated:YES];

The problem is this does not work. What specifically? The Y Position.

In each case, the selected node does get centered. However, the Y coordinate is totally screwy. If I add the adjustment, it goes up or down inversely to what I want it to. If I subtract it, it totally flies off screen. I don't know how to fix this.

Also, if I zoom a little, the X position gets flung off track too. I don't understand why. I've tried scaling the offset adjustment up or down based on the scaling, but it doesn't help.

This wasn't my only attempt. I've tried using the visible rect of the UIScrollView this way too:

[scrollView convertRect:scrollView.bounds
                             toView:[scrollView.delegate viewForZoomingInScrollView:scrollView]];

If someone could explain how to do this, it would be very much appreciated.

Fail Submition process of app store

iPhone app validates before submitting to app store but in submitting process they shows error.Why validation don't show those errors?

iOS Keyboard in Swift is too wide and tall when loading from XIB file

I'm building a keyboard using Swift (XCode 6 with iOS 8.3 SDK) and when I load the xib, the keyboard is about 1000 pixels too wide and tall. I've, in the freeform xib file, put all my keys in a UIView and set the UIViews constraints to superview top, bottom, left and right.

http://ift.tt/1LOUAOA

As you can see, the result is annoying. Here's my code:

import UIKit

class KeyboardViewController: UIInputViewController {

var BlurBoardView: UIView!

override func viewDidLoad() {
    super.viewDidLoad()
    loadInterface()
}

func loadInterface() {
    //load the nib file
    var blurboardNib = UINib(nibName: "BlurBoardView", bundle: nil)
    // initiate the view
    BlurBoardView = blurboardNib.instantiateWithOwner(self, options: nil)[0] as! UIView
    // add the interface to the main view
    view.addSubview(BlurBoardView)
    // copy the background color
    view.backgroundColor = BlurBoardView.backgroundColor

    let blur = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Light))
    blur.frame = view.frame
    view.addSubview(blur)
}

@IBAction func didTapButton(sender: AnyObject?) {

    let button = sender as! UIButton
    let title = button.titleForState(.Normal)
    var proxy = textDocumentProxy as! UITextDocumentProxy

    switch title as String!{
        case "<" :
            proxy.deleteBackward()
        case "RETURN" :
            proxy.insertText("\n")
        case " " :
            proxy.insertText(" ")
        case "CHG" :
            self.advanceToNextInputMode()
        default :
            proxy.insertText(title!)
    }
}

/*
override func textWillChange(textInput: UITextInput) {
    // The app is about to change the document's contents. Perform any preparation here.
}

override func textDidChange(textInput: UITextInput) {
    // The app has just changed the document's contents, the document context has been updated.

    var textColor: UIColor
    var proxy = self.textDocumentProxy as! UITextDocumentProxy
    if proxy.keyboardAppearance == UIKeyboardAppearance.Dark {
        textColor = UIColor.whiteColor()
    } else {
        textColor = UIColor.blackColor()
    }
    //self.nextKeyboardButton.setTitleColor(textColor, forState: .Normal)
}
*/
}

The keyboard, in it's precompiled xib looks like this:

http://ift.tt/1KiPACZ

You can also see the parent (of the keys) views constraints.

I'm mainly an Objective-C developer, so the code makes sense, but the issue might just be a huge SBE because of Swift, so sorry if it's ridiculously simple ;)

Thanks.

Content shows lower in UIScrollView when app first opened

I have my content in a UIView embedded in a UIScrollView showing lower than it should when I first open the view.

enter image description here

However, when I then click on any of the textfields, it scrolls up...

enter image description here

And returns exactly to the place where it is supposed to be

enter image description here

This is the code I am using:

- (void)keyboardWasShown:(NSNotification*)aNotification
{

    self.info = [aNotification userInfo];
    CGSize kbSize = [[self.info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
    self.scrollView.contentInset = contentInsets;
    self.scrollView.scrollIndicatorInsets = contentInsets;

    // If active text field is hidden by keyboard, scroll it so it's visible
    // Your app might not need or want this behavior.
    CGRect aRect = self.scrollView.frame;

    aRect.size.height -= kbSize.height;
    CGPoint origin = self.activeField.frame.origin;
    origin.y -= self.scrollView.contentOffset.y;
    //origin.y += activeField.frame.size.height;

    if (!CGRectContainsPoint(aRect, origin) ) {
        CGPoint scrollPoint = CGPointMake(0.0, self.activeField.frame.origin.y + self.activeField.frame.size.height - aRect.size.height);
        [self.scrollView setContentOffset:scrollPoint animated:YES];
    }

}

Works fine for iPad (landscape) but not for iPhone (portrait). Any ideas?

Thanks a lot!

Launch Apple Watch messages app from within another watchKit app

I want to launch the messages app on the Apple Watch from my own WatchKit app. I've seen this post here, but it only tells me to forward the app launch to the iPhone.

In the delegate method of the iPhone app, I can now perform a URL action. What's the URL I have to use in order to launch the messages app on the watch?

Update UILabel within a UITableViewCell

I am trying to update a UILabel within a Cell when a button within the cell is tapped. How would I go on as to approaching this. Here is my code for the creation of the UITableViewCell:

EDITED: On TAP Method

- (void)likeButtonTap:(InstagramLikeButton *)sender {
    [sender setSelected:!sender.selected];
    // Set objectID
    NSString *objectID = sender.objectID;
    int *likesCount = sender.likesCount;
    likesCount = likesCount + 1;
    NSString *likesString = [NSString stringWithFormat:@"%d",likesCount];
    // Get Cell
    NSIndexPath *i=[self indexPathForCellContainingView:sender.superview];
    InstagramCell *cell = (InstagramCell*)[self.tableView cellForRowAtIndexPath:i];
    cell.likeLabel = likesString;

    NSString *path = [NSString stringWithFormat:@"media/%@/likes", objectID];
    [[InstagramClient sharedClient] postPath:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Successfully Liked Picture");
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Failure: %@", error);
    }];
    [sender increaseLikeCount:sender];
    NSLog(@"Successfully Liked Picture");
}

Here is the error I am receiving:

Floadt[2669:176980] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString setText:]: unrecognized selector sent to instance 0x7f7f7a8bda50'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000107541c65 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x0000000106c7ebb7 objc_exception_throw + 45
    2   CoreFoundation                      0x00000001075490ad -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
    3   CoreFoundation                      0x000000010749f13c ___forwarding___ + 988
    4   CoreFoundation                      0x000000010749ecd8 _CF_forwarding_prep_0 + 120
    5   Floadt                              0x00000001036d455f -[InstagramTableViewController tableView:cellForRowAtIndexPath:] + 3663
    6   UIKit                               0x0000000105ab3a28 -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 508
    7   UIKit                               0x0000000105a92248 -[UITableView _updateVisibleCellsNow:isRecursive:] + 2853
    8   UIKit                               0x0000000105aa88a9 -[UITableView layoutSubviews] + 210
    9   UIKit                               0x0000000105a32a2b -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 536
    10  QuartzCore                          0x00000001057f6ec2 -[CALayer layoutSublayers] + 146
    11  QuartzCore                          0x00000001057eb6d6 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
    12  QuartzCore                          0x00000001057eb546 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
    13  QuartzCore                          0x0000000105757886 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 242
    14  QuartzCore                          0x0000000105758a3a _ZN2CA11Transaction6commitEv + 462
    15  QuartzCore                          0x000000010581a075 _ZN2CA7Display11DisplayLink14dispatch_itemsEyyy + 489
    16  CoreFoundation                      0x00000001074a9174 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 20
    17  CoreFoundation                      0x00000001074a8d35 __CFRunLoopDoTimer + 1045
    18  CoreFoundation                      0x000000010746ad3d __CFRunLoopRun + 1901
    19  CoreFoundation                      0x000000010746a366 CFRunLoopRunSpecific + 470
    20  GraphicsServices                    0x0000000109029a3e GSEventRunModal + 161
    21  UIKit                               0x00000001059b2900 UIApplicationMain + 1282
    22  Floadt                              0x000000010370ba6f main + 111
    23  libdyld.dylib                       0x000000010977e145 start + 1
    24  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException