简体   繁体   English

Objective-C样式的样式

[英]Objective-C category for styling

What is the best way to create re-usable styling for UI objects for iOS app? 为iOS应用程序创建UI对象的可重用样式的最佳方法是什么?

Eg I want to use the same style for each UITextField - top/bottom line and thinking about creating a category to provide the styling and simply apply it in View Controller. 例如,我想为每个UITextField使用相同的样式 - 顶部/底部线,并考虑创建一个类别以提供样式并简单地将其应用于View Controller。

Is there any better solution to do this? 有没有更好的解决方案呢?

UITextField+TextFieldStyler.m 的UITextField + TextFieldStyler.m

- (void)addTopBorderWithColor:(UIColor *)color
{
    CGRect topBorderFrame = CGRectMake(0, 0, self.bounds.size.width, 1.0);
    UIView *topBorder = [[UIView alloc] initWithFrame:topBorderFrame];
    topBorder.backgroundColor = color;

    [self addSubview:topBorder];
}

PXRLoginViewController.m PXRLoginViewController.m

[self.nameFIeld addTopBorderWithColor:[UIColor whiteColor]];
[self.passwordField addTopBorderWithColor:[UIColor whiteColor]];

I believe that the approach you are using is completely fine. 我相信你使用的方法完全没问题。 It's also used by Apple itself for the same use cases, looking at the doc 它也被Apple本身用于相同的用例,查看文档

Note: Cocoa and Cocoa Touch include a variety of categories for some of the primary framework classes. 注意: Cocoa和Cocoa Touch包含一些主要框架类的各种类别。

The string-drawing functionality mentioned in the introduction to this chapter is in fact already provided for NSString by the NSStringDrawing category for OS X, which includes the drawAtPoint:withAttributes: and drawInRect:withAttributes: methods. 本章简介中提到的字符串绘制功能实际上已经通过OS X的NSStringDrawing类别为NSString提供,其中包括drawAtPoint:withAttributes:和drawInRect:withAttributes:methods。 For iOS, the UIStringDrawing category includes methods such as drawAtPoint:withFont: and drawInRect:withFont:. 对于iOS,UIStringDrawing类别包括drawAtPoint:withFont:和drawInRect:withFont:等方法。

As you can see, they use the same pattern for extending the drawing behaviour of the NSString. 如您所见,它们使用相同的模式来扩展NSString的绘制行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM