Monday, September 30, 2013

UIStatusBarStyle PreferredStatusBarStyle does not work on iOS 7
down vote
favorite
In my iPhone application built with Xcode 5 for iOS 7 I set UIViewControllerBasedStatusBarAppearance=YES in info.plist, and in my ViewController I have this code:

-(void)UIStatusBarStyle PreferredStatusBarStyle ()
        {
            return UIStatusBarStyle.LightContent;
        }
But this code is not called and the status bar is still black against the black background.

I know its possible to change this app-wide by setting UIViewControllerBasedStatusBarAppearance=NO in info.plist, but I actually need to alter this on a viewController by viewController basis.
Intersection of line segment with axis-aligned box in C#
public static List<Point3D> IntersectionOfLineSegmentWithAxisAlignedBox(
    Point3D segmentBegin, Point3D segmentEnd, Point3D boxCenter, Size3D boxSize)
{
    var beginToEnd = segmentEnd - segmentBegin;
    var minToMax = new Vector3D(boxSize.X, boxSize.Y, boxSize.Z);
    var min = boxCenter - minToMax / 2;
    var max = boxCenter + minToMax / 2;
    var beginToMin = min - segmentBegin;
    var beginToMax = max - segmentBegin;
    var tNear = double.MinValue;
    var tFar = double.MaxValue;
    var intersections = new List<Point3D>();
    foreach (Axis axis in Enum.GetValues(typeof(Axis)))
    {
        if (beginToEnd.GetCoordinate(axis) == 0) // parallel
        {
            if (beginToMin.GetCoordinate(axis) > 0 || beginToMax.GetCoordinate(axis) < 0)
                return intersections; // segment is not between planes
        }
        else
        {
            var t1 = beginToMin.GetCoordinate(axis) / beginToEnd.GetCoordinate(axis);
            var t2 = beginToMax.GetCoordinate(axis) / beginToEnd.GetCoordinate(axis);
            var tMin = Math.Min(t1, t2);
            var tMax = Math.Max(t1, t2);
            if (tMin > tNear) tNear = tMin;
            if (tMax < tFar) tFar = tMax;
            if (tNear > tFar || tFar < 0) return intersections;

        }
    }
    if (tNear >= 0 && tNear <= 1) intersections.Add(segmentBegin + beginToEnd * tNear);
    if (tFar >= 0 && tFar <= 1) intersections.Add(segmentBegin + beginToEnd * tFar);
    return intersections;
}
public enum Axis
{
    X,
    Y,
    Z
}
public static double GetCoordinate(this Point3D point, Axis axis)
{
    switch (axis)
    {
        case Axis.X:
            return point.X;
        case Axis.Y:
            return point.Y;
        case Axis.Z:
            return point.Z;
        default:
            throw new ArgumentException();
    }
}

public static double GetCoordinate(this Vector3D vector, Axis axis)
{
    switch (axis)
    {
        case Axis.X:
            return vector.X;
        case Axis.Y:
            return vector.Y;
        case Axis.Z:
            return vector.Z;
        default:
            throw new ArgumentException();
    }
}
Intersection of line segment with axis-aligned box in C#
public static List<Point3D> IntersectionOfLineSegmentWithAxisAlignedBox(
    Point3D segmentBegin, Point3D segmentEnd, Point3D boxCenter, Size3D boxSize)
{
    var beginToEnd = segmentEnd - segmentBegin;
    var minToMax = new Vector3D(boxSize.X, boxSize.Y, boxSize.Z);
    var min = boxCenter - minToMax / 2;
    var max = boxCenter + minToMax / 2;
    var beginToMin = min - segmentBegin;
    var beginToMax = max - segmentBegin;
    var tNear = double.MinValue;
    var tFar = double.MaxValue;
    var intersections = new List<Point3D>();
    foreach (Axis axis in Enum.GetValues(typeof(Axis)))
    {
        if (beginToEnd.GetCoordinate(axis) == 0) // parallel
        {
            if (beginToMin.GetCoordinate(axis) > 0 || beginToMax.GetCoordinate(axis) < 0)
                return intersections; // segment is not between planes
        }
        else
        {
            var t1 = beginToMin.GetCoordinate(axis) / beginToEnd.GetCoordinate(axis);
            var t2 = beginToMax.GetCoordinate(axis) / beginToEnd.GetCoordinate(axis);
            var tMin = Math.Min(t1, t2);
            var tMax = Math.Max(t1, t2);
            if (tMin > tNear) tNear = tMin;
            if (tMax < tFar) tFar = tMax;
            if (tNear > tFar || tFar < 0) return intersections;

        }
    }
    if (tNear >= 0 && tNear <= 1) intersections.Add(segmentBegin + beginToEnd * tNear);
    if (tFar >= 0 && tFar <= 1) intersections.Add(segmentBegin + beginToEnd * tFar);
    return intersections;
}
public enum Axis
{
    X,
    Y,
    Z
}
public static double GetCoordinate(this Point3D point, Axis axis)
{
    switch (axis)
    {
        case Axis.X:
            return point.X;
        case Axis.Y:
            return point.Y;
        case Axis.Z:
            return point.Z;
        default:
            throw new ArgumentException();
    }
}

public static double GetCoordinate(this Vector3D vector, Axis axis)
{
    switch (axis)
    {
        case Axis.X:
            return vector.X;
        case Axis.Y:
            return vector.Y;
        case Axis.Z:
            return vector.Z;
        default:
            throw new ArgumentException();
    }
}

Public Methods


public abstract boolean cancel (boolean mayInterruptIfRunning)

Added in API level 5
Attempts to cancel execution of this task. This attempt will fail if the task has already completed, has already been cancelled, or could not be cancelled for some other reason. If successful, and this task has not started when cancelis called, this task should never run. If the task has already started, then the mayInterruptIfRunning parameter determines whether the thread executing this task should be interrupted in an attempt to stop the task.
After this method returns, subsequent calls to isDone() will always return true. Subsequent calls toisCancelled() will always return true if this method returned true.
Parameters
mayInterruptIfRunningtrue if the thread executing this task should be interrupted; otherwise, in-progress tasks are allowed to complete
Returns
  • false if the task could not be cancelled, typically because it has already completed normally; true otherwise

public abstract V getResult (long timeout, TimeUnit unit)

Added in API level 5
Accessor for the future result the AccountManagerFuture represents. This call will block until the result is available. In order to check if the result is available without blocking, one may call isDone() and isCancelled(). If the request that generated this result fails or is canceled then an exception will be thrown rather than the call returning normally. If a timeout is specified then the request will automatically be canceled if it does not complete in that amount of time.
Parameters
timeoutthe maximum time to wait
unitthe time unit of the timeout argument. This must not be null.
Returns
  • the actual result
Throws
OperationCanceledExceptionif the request was canceled for any reason
AuthenticatorExceptionif there was an error communicating with the authenticator or if the authenticator returned an invalid response
IOExceptionif the authenticator returned an error response that indicates that it encountered an IOException while communicating with the authentication server

Summary


Public Methods
abstract booleancancel(boolean mayInterruptIfRunning)
Attempts to cancel execution of this task.
abstract VgetResult(long timeout, TimeUnit unit)
Accessor for the future result the AccountManagerFuture represents.
abstract VgetResult()
Accessor for the future result the AccountManagerFuture represents.
abstract booleanisCancelled()
Returns true if this task was cancelled before it completed normally.
abstract booleanisDone()
Returns true if this task completed.

AccountManagerFuture

android.accounts.AccountManagerFuture<V>

Class Overview


AccountManagerFuture represents the result of an asynchronous AccountManager call. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation. The result can only be retrieved using method get when the computation has completed, blocking if necessary until it is ready. Cancellation is performed by the cancel method. Additional methods are provided to determine if the task completed normally or was cancelled. Once a computation has completed, the computation cannot be cancelled. If you would like to use a Future for the sake of cancellability but not provide a usable result, you can declare types of the form Future<?> and return null as a result of the underlying task.

Sunday, September 29, 2013

Cocoa Touch

Cocoa Touch is the programming framework driving user interaction on iOS. Using technology derived from Cocoa and the gorgeous Mac desktop, Cocoa Touch and the iOS interface were completely re-designed for multi-touch. Buttons, table lists, page transitions, and gestures on the iPhone are unique for the pocketable form factor, and all this UI power is available to developers through the Cocoa Touch frameworks.
Built upon the Model-View-Controller paradigm, Cocoa Touch provides a solid foundation for creating state-of-the-art applications. When combined with the Interface Builder developer tool, it is both easy and fun to use drag-and-drop to design the next great iOS application.
Strong low-level foundations enable fantastic high-level frameworks such as Game Kit for multiplayer gaming, Core Data, which offers high performance, yet easy-to-use data management, Core Animation for stunning effects, and the most innovative browser engine on mobile devices in WebKit.
Working together, the Cocoa Touch frameworks and powerful foundation provide a truly unique canvas upon which to create a new work of application art. Learn more

Powerful Foundation

Derived from core OS X technologies, the amazing user experience of iOS has been streamlined to take maximum advantage of iPhone, iPad, and iPod touch hardware. Technologies shared between iOS and OS X include the OS X kernel, BSD sockets for networking, and Objective-C and C/C++ compilers for native performance.

Develop Apps for iOS

The world’s most advanced mobile operating system.

iOS is the world’s most advanced mobile operating system, continually redefining what people can do with a mobile device. Together, the iOS SDK and Xcode IDE make it easy for developers to create revolutionary mobile apps.

 Assets

Whats are assets?
While the res directory contains structured values which are known to the Android platform, the assets directory can be used to store any kind of data.
While you could also store uses data in the /res/raw folder. If you need access to original file names and file hierarchy, you can save these resources in the assets directory.

Reference to resources in XML files

In your XML files, for example your layout files, you can refer to other resources via the @ sign.
For example, if you want to refer to a color which is defined in an XML resource, you can refer to it via @color/your_id. Or if you defined a "hello" string in an XML resource, you could access it via @string/hello.
To use an Android system resource, include the android namespace into the references, e.g. android.R.string.cancel.

 Accessing views from the layout in the activity

In your code you typically need to access the views in your activity or fragment to access and modify their properties.
In an activity you can use the findViewById(id) method call to search for a view in the current layout. The id is the ID attribute of the view in the layout. The usage of this method is demonstrated by the following code.
package com.vogella.android.first;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView = (TextView) findViewById(R.id.mytext);
        // TODO do something with the TextView
    }

} 

Thursday, September 26, 2013

Debugging OpenGL Frames
When debugging an OpenGL frame, the debug navigator shows the OpenGL call trace that generated the captured frame. The call trace includes the stack frame for each OpenGL call.
../art/debug_navigator-opengl_debugging_2x.png
The debug navigator contains the OpenGL call trace and a filter bar.
With the filter bar (the bottom box on the left in the screenshot) you specify the OpenGL calls and stack frames you want to see.
  • Call filter: Shows only markers and OpenGL draw calls.
  • Call stack slider: Shows stack frames, from only the most relevant to all of them.

About the Debug Navigator

The debug navigator displays the call stacks of your paused app. With this navigator you can debug C-based code and OpenGL frames.
Selecting an item in the debug navigator causes information about the item to be displayed in the editor area and in the debug area.

Debugging C-based Code
When debugging C-based code, the navigator groups the stack frames by threads or queues, and lists the memory locations you’re interested in. Use the debug navigator to navigate the stack frames of your app’s threads, and to manage viewed memory locations for the current debugging session.
The debug navigator opens automatically whenever you pause your application (by choosing Debug > Pause), or it hits a breakpoint. (You can change that behavior in Alerts preferences.)
../art/debug_navigator-c_debugging_2x.png
Threads indicate their running state with a status icon:
  • No icon means the thread is running normally.
  • A yellow status icon means that the thread is blocked and waiting on a lock or condition.
  • A red status icon means that you suspended the thread. A suspended thread does not execute code when you resume your application.
The debug navigator contains debug gauges, a scope selector, the thread and memory location list, and a filter bar.
With the debug gauges, you can see how your app is consuming cpu power, memory, and other attributes as it runs.
With the scope selector you indicate how the navigator displays threads:
  • By Thread: Displays threads as a flat list.
  • By Queue: Groups threads under the dispatch queue that created them.
With the filter bar you specify the threads and stack frames you want to see.
  • Thread filter: Shows only relevant threads.
  • Call stack slider: Shows stack frames, from only the most relevant to all of them.
To remove a memory location from the list, select it and press Delete.
If you are debugging multiple processes from the same workspace, each process is listed separately in the debug navigator with its threads grouped underneath it. Multiple process debugging is a useful way to debug the interactions between client and server processes.

Accessing views from the layout in the activity

In your code you typically need to access the views in your activity or fragment to access and modify their properties.
In an activity you can use the findViewById(id) method call to search for a view in the current layout. The id is the ID attribute of the view in the layout. The usage of this method is demonstrated by the following code.
package com.vogella.android.first;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView) findViewById(R.id.mytext);
// TODO do something with the TextView

Using Resources

Reference to resources in code

The Resources class allows to access individual resources. An instance of Resources can get access via the getResources() method of the Context class.
The Resources class is also used by other Android classes, for example the following code shows how to create a Bitmap file from a reference ID.
BitmapFactory.decodeResource(getResources(), R.drawable.ic_action_search);

Performance considerations with layouts

Calculating the layout and drawing the views is an resource intensive operation. You should use the most simple layout possible to archive good performance. For example you should avoid nesting layout managers too deeply or avoid using complex layout managers in case a simple layout manager is sufficient.

Predefining IDs via a separate file

Android allows that you define ID of user interface components dynamically in the layout files, via the@+id/your_id notation.
To control your IDs you can also create a file called ids.xml in your /res/values folder and define all IDs in this file.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="button1" type="id"/>
</resources>
This allow you to use the ID directly in your layout file.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="@id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_marginRight="27dp"
android:text="Button" />
/RelativeLayout>

Wednesday, September 25, 2013

Defining IDs

If a view needs to be accessed via Java code (see Section 19.2, “Accessing views from the layout in the activity ”), you have to give the View a unique ID via the android:id attribute. To assign a new ID to a View use . The following shows an example in which a @+id/yourvalue Button gets the button1 ID assigned.
<Button
  android:id="@+id/button1"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="Show Preferences" >
</Button> 
By conversion this will create and assign a new yourvalue ID to the corresponding view.

XML layout files

A layout resource file is referred to as layout. A layout specifies the ViewGroups, Views, their relationship and their attributes via an XML representation.
The following code is an example for a simple layout file.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/mytext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout> 
A layout is assigned to an activity via the setContentView() method calls, as demonstrated in the following example code.
package com.vogella.android.first;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

} 

Layout resource files

Activities and layouts

Android activities define their user interface with views (widgets) and fragments. This user interface can be defined via XML layouts resource files in the /res/layout folder or via Java code. You can also mix both approaches.
Defining layouts via XML layout files is usually the preferred way as this separates the programming logic from the layout definition. It also allows the definition of different layouts for different devices.
Run your app in Simulator to make sure that the UI elements you added look the way you expect them to. If you click the Hello button, it should highlight, and if you click inside the text field, the keyboard should appear. At the moment, though, the button doesn’t do anything, the label just displays “Label,” and there’s no way to dismiss the keyboard after it appears. To add the functionality you want, you need to make the appropriate connections between the UI elements and the view controller. These connections are described next.

Create an Action for the Button

When the user activates a UI element, the element can send an action message to an object that knows how to perform the corresponding action method (such as “add this contact to the user’s list of contacts”). This interaction is part of the target-action mechanism, which is another Cocoa Touch design pattern.
In this tutorial, when the user taps the Hello button, you want it to send a “change the greeting” message (the action) to the view controller (the target). This message changes the string (that is, the model object) that the view controller manages. Then, the view controller updates the text that’s displayed in the label to reflect the change in the model object’s value.
Using Xcode, you can add an action to a UI element and set up its corresponding action method by Control-dragging from the element on the canvas to the appropriate source file (typically, a view controller’s source file). The storyboard archives the connections that you create in this way. Later, when the app loads the storyboard, the connections are restored.
bullet
To add an action for the button
When you Control-dragged from the Hello button to the HelloWorldViewController.h file and configured the resulting action, you accomplished two things:
  • You added the appropriate code to the view controller class. Specifically, you added the following action method declaration to HelloWorldViewController.h:
    - (IBAction)changeGreeting:(id)sender;
    and caused Xcode to add the following stub implementation to HelloWorldViewController.m:
    - (IBAction)changeGreeting:(id)sender {
    }
  • You created a connection between the button and the view controller.
Next, you create connections between the view controller and the two remaining UI elements (that is, the label and the text field).

Add the User Interface Elements

You add user interface (UI) elements by dragging them from the object library to a view on the canvas. After the UI elements are in a view, you can move and resize them as appropriate.
bullet
To add the UI elements to the view and lay them out appropriately
After you add the text field, label, and button UI elements and make the recommended layout changes, your project should look similar to this:
../Art/after_layout.jpg
There are a few other changes you can make to the text field so that it behaves as users expect. First, because users will be entering their names, you can ensure that iOS suggests capitalization for each word they type. Second, you can make sure that the keyboard associated with the text field is configured for entering names (rather than numbers, for example), and that the keyboard displays a Done button.
This is the principle behind these changes: Because you know at design time what type of information a text field will contain, you can configure it so that its runtime appearance and behavior are well suited to the user’s task. You make all of these configuration changes in the Attributes inspector.

Tuesday, September 24, 2013

Predefining IDs via a separate file

Android allows that you define ID of user interface components dynamically in the layout files, via the @+id/your_id notation.
To control your IDs you can also create a file called ids.xml in your /res/values folder and define all IDs in this file.
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="button1" type="id"/>
</resources> 
This allow you to use the ID directly in your layout file.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <Button
        android:id="@id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="27dp"
        android:text="Button" />

</RelativeLayout>