UIColor
的分类。但是问题在于,在Xcode 6中没有Objective-C分类文件模板。是否有任何选项可以在Xcode 6中创建一个分类?
UIColor
的分类。但是问题在于,在Xcode 6中没有Objective-C分类文件模板。他们没有忘记,只是在没有告知任何人的情况下将其移动了。
点击 File
-> New
-> File
在 iOS
或 Mac OS
下选择 Sources
中的 Objective-C file
并单击 Next
现在在 File Type:
下选择 Category
、Protocol
或 Extension
PS. 在 File Name:
下,您输入的任何内容都将成为 Category
、Protocol
或 Extension
的名称。
Xcode6-Beta5更新
界面已经更改,现在可以直接从新建文件窗口添加分类。
参见unmircea的答案。
我自己也感到惊讶,我猜是因为Swift,他们忘记了好老的Objective-C。
你有两个选择:
创建一个带有分类名称的Objective-C类,例如UIView+Powerups
,然后手动更改接口以匹配该类别的接口。请注意,类别接口和实现的代码片段仍然可用,所以这很容易:键入@interface-category
和@implementation-category
。
从Xcode 5中导入它!使用此命令:
sudo cp -R /Applications/Xcode5.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/Xcode/Templates/File\ Templates/Cocoa\ Touch/Objective-C\ category.xctemplate /Applications/Xcode6-Beta5.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/Xcode/Templates/File\ Templates/Cocoa\ Touch/
cp -r /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/Xcode/Templates/File\ Templates/Cocoa\ Touch/Objective-C\ category.xctemplate /Applications/Xcode6-Beta.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/Xcode/Templates/File\ Templates/Source/
关闭并重新打开Xcode 6,然后在新文件向导中会找到“Objective-C类别”。目前在Xcode 6 beta中还没有预定义的创建类别的模板,他们可能稍后会添加此选项。作为一种解决方法,您可以创建一个名为UIImage+Additions
的Cocoa Touch Class
(我知道这不是合适的方式,但没有其他方式),并覆盖其界面和实现,例如:
#import <UIKit/UIKit.h>
@interface UIImage(Additions)
+(void)testMethod;
@end
#import "UIImage+Additions.h"
@implementation UIImage (Additions)
+(void)testMethod
{
}
@end
编辑
在发现Xcode 6 beta中创建类别的正确方式之前,编写了此答案。请查看unmircea的答案获取正确的创建类别方式。
扩展unmircea的精彩答案,关于如何创建一个自定义UIColor
调色板的自定义类别,您可以创建一个类别。
一旦您创建了您的类别(在这个例子中,它是一个名为ColorPalette
的类别,属于类UIColor
),您将拥有一个头文件和一个实现文件。
UIColor+ColorPalette.h
#import <UIKit/UIKit.h>
@interface UIColor (ColorPalette)
// Your custom colors
+ (UIColor *) customRedButtonColor;
+ (UIColor *) customGreenButtonColor;
@end
UIColor+ColorPalette.m
#import "UIColor+ColorPalette.h"
@implementation UIColor (ColorPalette)
// Button Colors
+ (UIColor *) customRedButtonColor {
return [UIColor colorWithRed:178.0/255.0 green:25.0/255.0 blue:0.0/255.0 alpha:1.0];
}
+ (UIColor *) customGreenButtonColor {
return [UIColor colorWithRed:20.0/255.0 green:158.0/255.0 blue:96.0/255.0 alpha:1.0];
}
#import "UIColor+ColorPalette.h"
您可以像调用标准颜色(例如redColor
、greenColor
或blueColor
)一样调用该颜色。
1: File → New → File... or use ⌘N.
2: Name NSString+Helper (For example)
3: create the file
4: Remove the code from file
5: add
extension NSString {
}
完成。享受编程吧。
@interface UIColor(MyCategory) ...
等。 - JeremyP