Objective C NSView具有渐变背景

@interface ColorGradientView : NSView
{
  NSColor *startingColor;
  NSColor *endingColor;
  int angle;
}

// Define the variables as properties
@property(nonatomic, retain) NSColor *startingColor;
@property(nonatomic, retain) NSColor *endingColor;
@property(assign) int angle;

@end

@implementation ColorGradientView

// Automatically create accessor methods
@synthesize startingColor;
@synthesize endingColor;
@synthesize angle;

- (id)initWithFrame:(NSRect)frame;
{
  if (self = [super initWithFrame:frame]) {
    [self setStartingColor:[NSColor colorWithCalibratedWhite:1.0 alpha:1.0]];
    [self setEndingColor:nil];
    [self setAngle:270];
  }
  return self;
}

- (void)drawRect:(NSRect)rect;
{
  if (endingColor == nil || [startingColor isEqual:endingColor]) {
    // Fill view with a standard background color
    [startingColor set];
    NSRectFill(rect);
  }
  else {
    // Fill view with a top-down gradient
    // from startingColor to endingColor
    NSGradient* aGradient = [[[NSGradient alloc]
        initWithStartingColor:startingColor
        endingColor:endingColor] autorelease];
    [aGradient drawInRect:[self bounds] angle:angle];
  }
}

- (void)setStartingColor:(NSColor *)newColor;
{
	[startingColor autorelease];
	startingColor = [newColor retain];
	
	[self setNeedsDisplay:YES];
}

- (void)setEndingColor:(NSColor *)newColor;
{
	[endingColor autorelease];
	endingColor = [newColor retain];
	
	[self setNeedsDisplay:YES];
}

- (void)dealloc;
{
	[self setStartingColor:nil];
	[self setEndingColor:nil];
	[super dealloc];
}

@end

Objective C 使用图案图像绘制背景的正确方法

// Save the current graphics state first so we can restore it.
[[NSGraphicsContext currentContext] saveGraphicsState];

// Change the pattern phase.
[[NSGraphicsContext currentContext] setPatternPhase:
    NSMakePoint(0,[self frame].size.height)];

// Stick the image in a color and fill the view with that color.
NSImage *anImage = [NSImage imageNamed:@"bricks"];
[[NSColor colorWithPatternImage:anImage] set];
NSRectFill([self bounds]);

// Restore the original graphics state.
[[NSGraphicsContext currentContext] restoreGraphicsState];

Objective C 在细胞界限内绘制标准聚焦环

- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView;
{
    // other stuff might happen here
    if ([self showsFirstResponder]) {
         // showsFirstResponder is set for us by the NSControl that is drawing  us.
        NSRect focusRingFrame = cellFrame;
        focusRingFrame.size.height -= 2.0f;
        [NSGraphicsContextsaveGraphicsState];
        NSSetFocusRingStyle(NSFocusRingOnly);
        [[NSBezierPath bezierPathWithRect: NSInsetRect(focusRingFrame, 4.0f, 4.0f)] fill];
        [NSGraphicsContext restoreGraphicsState];
    }
    // other stuff might happen here
}

Objective C 初始化和填充一系列Sprite

for (int i = 0; i < 9; i++ ) {
//create a slot object with a label
//add the object to the slots array

//sprite
	[slots addObject: [[[Slot alloc] initWithSprite:[CCSprite spriteWithFile:@"hole.png"]
		withPos_x:count%3*cellWidth+offset_x
		withPos_y:count/3*cellHeight+offset_y
		isOccupied:NO] autorelease]];

//add the sprite to the layer
	[self addChild: ((Slot*) [slots objectAtIndex:i]).sprite];

	count++;
}

Objective C NSView具有渐变背景

@interface ColorGradientView : NSView
{
  NSColor *startingColor;
  NSColor *endingColor;
  int angle;
}

// Define the variables as properties
@property(nonatomic, retain) NSColor *startingColor;
@property(nonatomic, retain) NSColor *endingColor;
@property(assign) int angle;

@end

@implementation ColorGradientView

// Automatically create accessor methods
@synthesize startingColor;
@synthesize endingColor;
@synthesize angle;

- (id)initWithFrame:(NSRect)frame;
{
  if (self = [super initWithFrame:frame]) {
    [self setStartingColor:[NSColor colorWithCalibratedWhite:1.0 alpha:1.0]];
    [self setEndingColor:nil];
    [self setAngle:270];
  }
  return self;
}

- (void)drawRect:(NSRect)rect;
{
  if (endingColor == nil || [startingColor isEqual:endingColor]) {
    // Fill view with a standard background color
    [startingColor set];
    NSRectFill(rect);
  }
  else {
    // Fill view with a top-down gradient
    // from startingColor to endingColor
    NSGradient* aGradient = [[[NSGradient alloc]
        initWithStartingColor:startingColor
        endingColor:endingColor] autorelease];
    [aGradient drawInRect:[self bounds] angle:angle];
  }
}

- (void)setStartingColor:(NSColor *)newColor;
{
	[startingColor autorelease];
	startingColor = [newColor retain];
	
	[self setNeedsDisplay:YES];
}

- (void)setEndingColor:(NSColor *)newColor;
{
	[endingColor autorelease];
	endingColor = [newColor retain];
	
	[self setNeedsDisplay:YES];
}

- (void)dealloc;
{
	[self setStartingColor:nil];
	[self setEndingColor:nil];
	[super dealloc];
}

@end

Objective C iPhone:在库中定义类别实际上是有效的

//CategoryBugHack.h
#define FIX_CATEGORY_BUG(name) @interface FIX_CATEGORY_BUG##name @end @implementation FIX_CATEGORY_BUG##name @end
Then the category .h/.m ...

//NSStringCategory.h
@interface NSString (MyAdditions)
// etc, etc
@end

//NSStringCategory.m
#import "CategoryBugHack.h"
FIX_CATEGORY_BUG(NSString_MyAdditions)
@implementation NSString (MyAdditions)
// etc, etc
@end

Objective C Android:获取设备的唯一ID

There are many answers to this question, most of which will only work "some" of the time, and unfortunately that's not good enough.

Based on my tests of devices (all phones, at least one of which is not activated):

All devices tested returned a value for TelephonyManager.getDeviceId()
All GSM devices (all tested with a SIM) returned a value for TelephonyManager.getSimSerialNumber()
All CDMA devices returned null for getSimSerialNumber() (as expected)
All devices with a Google account added returned a value for ANDROID_ID
All CDMA devices returned the same value (or derivation of the same value) for both ANDROID_ID and TelephonyManager.getDeviceId() -- as long as a Google account has been added during setup.
I did not yet have a chance to test GSM devices with no SIM, a GSM device with no Google account added, or any of the devices in airplane mode.
So if you want something unique to the device itself, TM.getDeviceId() should be sufficient. Obviously some users are more paranoid than others, so it might be useful to hash 1 or more of these identifiers, so that the string is still virtually unique to the device, but does not explicitly identify the user's actual device. For example, using String.hashCode(), combined with a UUID:

    final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);

    final String tmDevice, tmSerial, tmPhone, androidId;
    tmDevice = "" + tm.getDeviceId();
    tmSerial = "" + tm.getSimSerialNumber();
    androidId = "" + android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);

    UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDevice.hashCode() << 32) | tmSerial.hashCode());
    String deviceId = deviceUuid.toString();
might result in something like: 00000000-54b3-e7c7-0000-000046bffd97

It works well enough for me.

As Richard mentions below, don't forget that you need permission to read the TelephonyManager properties, so add this to your manifest:

<uses-permission android:name="android.permission.READ_PHONE_STATE" />

Objective C 从第一个视图控制器链接到新的视图控制器

#import "VCExampleViewController.h"
//---import the header file for the view controller---
#import "SecondViewController.h"
 
@implementation VCExampleViewController
SecondViewController *secondViewController;
//---add the view of the second view controller to the current view---
-(IBAction) displayView:(id) sender{
    secondViewController = [[SecondViewController alloc] 
                                    initWithNibName:@"SecondView" 
                                    bundle:nil];
    [self.view addSubview:secondViewController.view];
}
- (void)dealloc {
    //---release the memory used by the view controller---
    [secondViewController release];
    [super dealloc];
} 
@end

Objective C 如何制作圆角图像

void addRoundedRectToPath(CGContextRef context, CGRect rect, float ovalWidth, float ovalHeight);
{
	float fw, fh;
	if (ovalWidth == 0 || ovalHeight == 0) {
		CGContextAddRect(context, rect);
		return;
	}
	CGContextSaveGState(context);
	CGContextTranslateCTM (context, CGRectGetMinX(rect), CGRectGetMinY(rect));
	CGContextScaleCTM (context, ovalWidth, ovalHeight);
	fw = CGRectGetWidth (rect) / ovalWidth;
	fh = CGRectGetHeight (rect) / ovalHeight;
	CGContextMoveToPoint(context, fw, fh/2);
	CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1);
	CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1);
	CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1);
	CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1);
	CGContextClosePath(context);
	CGContextRestoreGState(context);
}

- (UIImage *)roundCornersOfImage:(UIImage *)source;
{
	int w = source.size.width;
	int h = source.size.height;
	
	CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
	CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);
	
	CGContextBeginPath(context);
	CGRect rect = CGRectMake(0, 0, w, h);
	addRoundedRectToPath(context, rect, 5, 5);
	CGContextClosePath(context);
	CGContextClip(context);
	
	CGContextDrawImage(context, CGRectMake(0, 0, w, h), source.CGImage);
	
	CGImageRef imageMasked = CGBitmapContextCreateImage(context);
	CGContextRelease(context);
	CGColorSpaceRelease(colorSpace);
	
	return [UIImage imageWithCGImage:imageMasked];    
}

Objective C 使用CLLocationManager从Ipad获取GPS

// view controller .h file

#import <CoreLocation/CoreLocation.h>
@interface StoreInputViewController : UIViewController <CLLocationManagerDelegate> {
    ...
    CLLocationManager *locationManager;
}

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation;

// view controller .m file

// init the location manager in the viewDidLoad
- (void)viewDidLoad
{
    [super viewDidLoad];
   
    // initialize the GPS
    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
}

// check whether GPS is enabled
- (BOOL) isGPSEnabled
{
    if (! ([CLLocationManager  locationServicesEnabled])
        || ( [CLLocationManager  authorizationStatus] == kCLAuthorizationStatusDenied))
    {
        return NO;
    }
    return YES;
}

// function to start capture GPS, we check settings first to see if GPS is disabled before attempting to get GPS
- (void) getGPS
{
    if([self isGPSEnabled])
    {
        // Location Services is not disabled, get it now
        [locationManager startUpdatingLocation];
    }
    else        
    {
        // Location Services is disabled, do sth here to tell user to enable it
    }
} 

// receiving the gps and stop it immediately (one time gps only for this example)
- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
    int degrees = newLocation.coordinate.latitude;
    double decimal = fabs(newLocation.coordinate.latitude - degrees);
    int minutes = decimal * 60;
    double seconds = decimal * 3600 - minutes * 60;
    NSString *latValue = [NSString stringWithFormat:@"%d° %d' %1.4f\"", 
                     degrees, minutes, seconds];
    
    degrees = newLocation.coordinate.longitude;
    decimal = fabs(newLocation.coordinate.longitude - degrees);
    minutes = decimal * 60;
    seconds = decimal * 3600 - minutes * 60;
    NSString *longValue = [NSString stringWithFormat:@"%d° %d' %1.4f\"", 
                       degrees, minutes, seconds];
    
    NSLog(@"Lat: %@ Long:%@", latValue, longValue);
    
    // stop updating
    [manager stopUpdatingLocation];
}