Objective C 分段控制使用

#define ACTIONEDIT  0
#define ACTIONADD   1
...
UISegmentedControl* segmentedControl = [[UISegmentedControl alloc] 
       initWithItems: [NSArray arrayWithObjects: 
         [UIImage imageNamed:@"icon-edit.png"], 
         [UIImage imageNamed:@"icon-add.png"],
         nil]
       ];
[segmentedControl addTarget:self 
                     action:@selector(segmentAction:) 
           forControlEvents:UIControlEventValueChanged];

segmentedControl.frame = CGRectMake(0, 0, 90, 30);
segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
segmentedControl.momentary = YES;
[segmentedControl setEnabled:YES forSegmentAtIndex:ACTIONEDIT];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
                       initWithCustomView:segmentedControl];

...

- (void)segmentAction:(id)sender
{
  UISegmentedControl* segCtl = sender;
  int action = [segCtl selectedSegmentIndex];
  switch (action) {
    case ACTIONADD:
     [self addToList];
     break;
    case ACTIONEDIT:
     [self editList];
     break;
  }
}

Objective C UINavigationItem中的UISegmentedControl

UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:
											[NSArray arrayWithObjects:
											 [UIImage imageNamed:K_IMAGE_UPARROW],
											 [UIImage imageNamed:K_IMAGE_DOWNARROW],
											 nil]];
//[segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
segmentedControl.frame = CGRectMake(0, 0, 90, 30);
segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
segmentedControl.momentary = YES;
	
UIBarButtonItem *segmentBarItem = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl];
[segmentedControl release];
    
self.navigationItem.rightBarButtonItem = segmentBarItem;
[segmentBarItem release];

Objective C iPhone:调整UILabel的大小以适应其中的文本

// resize description label to fit text..
			UIFont* font = descriptionLabel.font;			
			CGSize constraintSize = CGSizeMake(descriptionLabel.frame.size.width, MAXFLOAT);
			CGSize labelSize = [descriptionLabel.text sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
			descriptionLabel.frame = CGRectMake(descriptionLabel.frame.origin.x, descriptionLabel.frame.origin.y, descriptionLabel.frame.size.width, labelSize.height);

// if the label's in a UIScrollView, and the label is at the bottom, here's how
// to make it scroll correctly.
// make the size of the scroll view be the distance from the top to the bottom of the 
// description label.
			scrollView.contentSize = CGSizeMake(scrollView.contentSize.width, descriptionLabel.frame.origin.y + descriptionLabel.frame.size.height);

Objective C UIActionSheet取消按钮奇怪的行为

//This will fix the problem when clicking on the cancel button of an actionsheet inside a Tab Bar Controller
[actionSheet showInView:self.parentViewController.tabBarController.view];

Objective C TextField输入完成后,ScrollView不响应

==============================
DECLARATION FILE
==============================
@interface ScrollViewViewController : UIViewController <UIScrollViewDelegate, UITextFieldDelegate>
{
	UIScrollView *m_scrollView;
	UITextField *m_textField1;
	UITextField *m_textField2;
}

@property(nonatomic,retain) IBOutlet UIScrollView *m_scrollView;
@property(nonatomic,retain) IBOutlet UITextField *m_textField1;
@property(nonatomic,retain) IBOutlet UITextField *m_textField2;

- (void)scrollViewToCenterOfScreen:(UIView *)theView;

@end

==============================
IMPLEMENTATION FILE
==============================
- (void)viewDidLoad {
    [super viewDidLoad];
	
	m_scrollView.contentSize = CGSizeMake(320, 1000);
	[self.view addSubview:m_scrollView];
}

...
#pragma mark * TextField Delegate Methods
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
	[textField resignFirstResponder];
	return NO;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
	[self scrollViewToCenterOfScreen:textField];
}

- (void)scrollViewToCenterOfScreen:(UIView *)theView 
{  
	CGRect keyboardBounds;
    CGFloat viewCenterY = theView.center.y;  
    CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];  
	
    CGFloat availableHeight = applicationFrame.size.height - keyboardBounds.size.height;    // Remove area covered by keyboard  
	
    CGFloat y = viewCenterY - availableHeight / 2.0;  
    if (y < 0) {  
        y = 0;  
    }  
    m_scrollView.contentSize = CGSizeMake(applicationFrame.size.width, applicationFrame.size.height + keyboardBounds.size.height);  
    [m_scrollView setContentOffset:CGPointMake(0, y) animated:YES];
}

Objective C UDIDå?? - å¾-

NSString *udid = [[UIDevice currentDevice] uniqueIdentifier];

Objective C 塞拉†...一个??«UIView作æ?

UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell               = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        
        UILabel* detailTextLabel = [[UILabel alloc] initWithFrame:CGRectMake(70.0f, 11.0f, 200.0f, 21.0f)];
        detailTextLabel.userInteractionEnabled = NO;
        detailTextLabel.backgroundColor = [UIColor clearColor];
        detailTextLabel.clipsToBounds   = YES;
        detailTextLabel.textAlignment   = UITextAlignmentRight;
        detailTextLabel.textColor       = [UIColor colorWithRed:0.03f green:0.42f blue:0.71f alpha:1.0f];
        detailTextLabel.highlightedTextColor = [UIColor whiteColor];
        detailTextLabel.tag = 99;
        detailTextLabel.font = [UIFont systemFontOfSize:17.0f];
        [cell.contentView addSubview:detailTextLabel];
        [detailTextLabel release];
        
        cell.textLabel.backgroundColor = [UIColor clearColor];
        cell.textLabel.textColor       = [UIColor colorWithRed:0.0f green:0.18f blue:0.27f alpha:1.0f];
        cell.textLabel.font            = [UIFont systemFontOfSize:17.0f];
        [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
    }
    
    UILabel* detailTextLabel = (UILabel*)[cell.contentView viewWithTag:99];

Objective C plistã,'NSDictionaryã?«ã€,

NSString *pathGenre = [[NSBundle mainBundle] pathForResource:@"Genre" ofType:@"plist"];
dict = [NSDictionary dictionaryWithContentsOfFile:pathGenre];

Objective C libxmlã??®ãƒ'ã,¹ã??®è¨å®(libxml路径设置)

${SDKROOT}/usr/include/ libxml2

Objective C 使用NSURLConnection中的libxml2

/*
 Add follow the path to search path of your project
 ${SDKROOT}/usr/include/libxml2
 Add follow the framework to your project
 libxml2.dylib

 1. Define your parse class with XMLDownloadParseDelegate protocol
 2. Instance XMLDownloadParse with your parse class
 3. Instance NSURLConnection and begin downloading
 4. Call connection:didReceiveResponse: and connection:didReceiveData: corresponding to NSURLConnection delegate
 5. Parse in your parse class as you like
 */

// XMLDownloadParse.h

#import <Foundation/Foundation.h>
#import <libxml/tree.h>

struct _xmlElementTag {
    const unsigned char *localneme;
    const unsigned char *prefix;
    const unsigned char *URI;
};

struct _xmlElementTagNamespaces {
    int nb_namespaces;
    const unsigned char **namespaces;
    int nb_attributes;
    int nb_defaulted;
    const unsigned char **attributes;
};

typedef struct _xmlElementTag xmlElementTag;
typedef struct _xmlElementTagNamespaces xmlElementTagNamespaces;

@protocol XMLDownloadParseDelegate

- (void)startElementTag:(xmlElementTag *)tag
         WithNamespaces:(xmlElementTagNamespaces *)tagNamespace;
- (void)endElementTag:(xmlElementTag *)tag;
- (void)charactersFound:(const unsigned char *)ch len:(int)len;

@end

@interface XMLDownloadParse : NSObject {
	xmlParserCtxtPtr ptrContext;
	id<XMLDownloadParseDelegate> delegate;
}

@property(nonatomic, retain) id<XMLDownloadParseDelegate> delegate;

- (id)initWithDelegate:(id<XMLDownloadParseDelegate>)aDelegate;
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;

- (void)startElementLocalName:(const xmlChar *)localname
                       prefix:(const xmlChar *)prefix
                          URI:(const xmlChar *)URI 
                nb_namespaces:(int)nb_namespaces 
                   namespaces:(const xmlChar **)namespaces 
                nb_attributes:(int)nb_attributes 
                 nb_defaulted:(int)nb_defaulted 
                   attributes:(const xmlChar **)attributes;
- (void)endElementLocalName:(const xmlChar *)localname 
                     prefix:(const xmlChar *)prefix
                        URI:(const xmlChar *)URI;
- (void)charactersFound:(const xmlChar *)ch 
                    len:(int)len;

@end

// XMLDownloadParse.m 
#import "XMLDownloadParse.h"

static void startElementHandler(
                                void *ctx, 
                                const xmlChar *localname, 
                                const xmlChar *prefix, 
                                const xmlChar *URI, 
                                int nb_namespaces, 
                                const xmlChar **namespaces, 
                                int nb_attributes, 
                                int nb_defaulted, 
                                const xmlChar **attributes)
{
    [(XMLDownloadParse*)ctx 
     startElementLocalName:localname 
     prefix:prefix URI:URI 
     nb_namespaces:nb_namespaces 
     namespaces:namespaces 
     nb_attributes:nb_attributes 
     nb_defaulted:nb_defaulted 
     attributes:attributes];
}

static void endElementHandler(
                              void *ctx, 
                              const xmlChar *localname, 
                              const xmlChar *prefix, 
                              const xmlChar *URI)
{
    [(XMLDownloadParse*)ctx 
     endElementLocalName:localname 
     prefix:prefix 
     URI:URI];
}

static void charactersFoundHandler(
                                   void *ctx, 
                                   const xmlChar *ch, 
                                   int len)
{
    [(XMLDownloadParse*)ctx 
     charactersFound:ch len:len];
}

static xmlSAXHandler _saxHandlerStruct = {
    NULL,           /* internalSubset */
    NULL,           /* isStandalone   */
    NULL,           /* hasInternalSubset */
    NULL,           /* hasExternalSubset */
    NULL,           /* resolveEntity */
    NULL,           /* getEntity */
    NULL,           /* entityDecl */
    NULL,           /* notationDecl */
    NULL,           /* attributeDecl */
    NULL,           /* elementDecl */
    NULL,           /* unparsedEntityDecl */
    NULL,           /* setDocumentLocator */
    NULL,           /* startDocument */
    NULL,           /* endDocument */
    NULL,           /* startElement*/
    NULL,           /* endElement */
    NULL,           /* reference */
    charactersFoundHandler, /* characters */
    NULL,           /* ignorableWhitespace */
    NULL,           /* processingInstruction */
    NULL,           /* comment */
    NULL,           /* warning */
    NULL,           /* error */
    NULL,           /* fatalError //: unused error() get all the errors */
    NULL,           /* getParameterEntity */
    NULL,           /* cdataBlock */
    NULL,           /* externalSubset */
    XML_SAX2_MAGIC, /* initialized */
    NULL,           /* private */
    startElementHandler,    /* startElementNs */
    endElementHandler,      /* endElementNs */
    NULL,           /* serror */
};

@implementation XMLDownloadParse

@synthesize delegate;

- (id)initWithDelegate:(id<XMLDownloadParseDelegate>)aDelegate{
    if (self = [super init]) {
        self.delegate = aDelegate;
    }
    return self;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    if (ptrContext) {
        xmlFreeParserCtxt(ptrContext);
    }
    ptrContext = xmlCreatePushParserCtxt(&_saxHandlerStruct,self,NULL,0,NULL);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    xmlParseChunk(ptrContext, (const char *)[data bytes], [data length], 0);
}

- (void)dealloc {
    self.delegate = nil;
    if (ptrContext) {
        xmlFreeParserCtxt(ptrContext);
        ptrContext = NULL;
    }
    [super dealloc];
}

- (void)startElementLocalName:(const xmlChar *)localname 
                       prefix:(const xmlChar *)prefix 
                          URI:(const xmlChar *)URI 
                nb_namespaces:(int)nb_namespaces 
                   namespaces:(const xmlChar **)namespaces 
                nb_attributes:(int)nb_attributes 
                 nb_defaulted:(int)nb_defaulted 
                   attributes:(const xmlChar **)attributes
{
    xmlElementTag tag;
    tag.localneme = localname;
    tag.prefix = prefix;
    tag.URI = URI;
    
    xmlElementTagNamespaces tagName;
    tagName.nb_namespaces = nb_namespaces;
    tagName.namespaces = namespaces;
    tagName.nb_attributes = nb_attributes;
    tagName.nb_defaulted = nb_defaulted;
    tagName.attributes = attributes;
    
    [self.delegate startElementTag:&tag WithNamespaces:&tagName];
}

- (void)endElementLocalName:(const xmlChar *)localname 
                     prefix:(const xmlChar *)prefix
                        URI:(const xmlChar *)URI
{
    xmlElementTag tag;
    tag.localneme = localname;
    tag.prefix = prefix;
    tag.URI = URI;
	
    [self.delegate endElementTag:&tag];
}

- (void)charactersFound:(const xmlChar *)ch 
                    len:(int)len
{
    [self.delegate charactersFound:ch len:len];
}

@end