2015-10-14 36 views
1

是否可以輕鬆地更改我的應用程序內某種類型的所有對象? 例如,更改所有UILabels的字體/顏色或在所有UILabels上應用setAdjustsFontSizeToFitWidth:函數。如何更改應用程序中文本字段類型的所有對象?

+0

你可以嘗試方法swizzling。您可以將原始選擇器或類型的方法調整爲自定義選擇器或方法。在這裏閱讀更多關於它的內容 - http://nshipster.com/method-swizzling/。 HTH :) – iamyogish

+0

您可以使用UIAppearance自定義整個UIKit控件類的外觀https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIAppearance_Protocol/index.html –

+0

您可以使用'子類'選項可以在項目中設置每個「UILabel」的特定屬性。閱讀更多關於['子類'這裏]的詳細信息(https://www.objc.io/issues/13-architecture/subclassing/) –

回答

0

您可以使用下面的代碼更改寬度,顏色,尺寸textfield或任何對象。

for(UITextField *txt in self.view.subviews) 
    { 
     if([txt isKindOfClass:[UITextField class]]) 
     { 
      //here do your work 
      txt.frame=CGRectMake(0, 50, 100, 100);//set size,color anything your want. 
     } 
    } 

使您想要使用的對象的類。

0

嘗試使用以下UIView類別:

的UIView + MakeChange.h

@import UIKit; 

@interface UIView (MakeChange) 
    +(void)makeChangeInView:(UIView*)superview 
        withBlock:(void(^)(__kindof UIView* view))block; 
@end 

的UIView + MakeChange.m

#import "UIView+MakeChange.h" 

@implementation UIView (MakeChange) 

+(void)makeChangeInView:(UIView*)superview 
       withBlock:(void(^)(__kindof UIView* view))block 
{ 
    if(!block || !superview) return; 

    for(UIView* subview in superview.subviews) 
    { 
     // Make changes to all subviews recursively 
     [self makeChangeInView:subview withBlock:block]; 

     if([subview isKindOfClass:self.class]) 
      block(subview); 
    } 
} 

@end 

您可以更改字體/每個當前顯示的顏色使用UILabel驗證碼:

[UILabel makeChangeInView:[[[UIApplication sharedApplication] windows] firstObject] 
       withBlock:^(UILabel* label) { 
    [label setTextColor:[UIColor redColor]]; 
    [label setFont:[UIFont systemFontOfSize:10.0]]; 
}]; 
  • 顯然,同樣的類可以用於任何UIView子類,以及(UITextFieldUIButton等)
  • ,請謹慎使用,特別是如果你的UI是複雜的 - 所有工作是在UI線程上完成的(沒有其他簡單的選擇),並且你不想阻塞它太長時間...出於同樣的原因,儘量避免將它用於主應用程序窗口(如我的示例中所示) 。
相關問題