2015-05-24 126 views
1

我有這樣的形象自定義視圖,並將其作品(文字字體和文本顏色我在設置的drawRectIBDesignable查看渲染

+ **************** *** +

*文本01IMAGE *

*文本02 _______ *

+ ********** ********* +

現在我想設置字體和顏色從接口Builde,但我得到的錯誤:

IB Designables: Failed to render instance of AvailableSeatView: Rendering the view took longer than 200 ms. Your drawing code may suffer from slow performance.

這裏我的代碼:

在AvailableSeatView.h

#import <UIKit/UIKit.h> 
IB_DESIGNABLE 
@interface AvailableSeatView : UIView 
@property (nonatomic) IBInspectable UIImage *image; 
@property (nonatomic) IBInspectable NSInteger numberSeats; 
@property (nonatomic) IBInspectable UIFont *numberSeatsFont; 
@property (nonatomic) IBInspectable UIColor *numberSeatsColor; 
@property (nonatomic) IBInspectable NSString *title; 

在AvailableSeatView.m

@implementation AvailableSeatView 
- (void)drawRect:(CGRect)rect { 
    //UIImage 
    CGRect myFrame = self.bounds; 
    CGFloat yImage = myFrame.size.height/2 - self.image.size.height < 0 ? 0 : myFrame.size.height/2 - self.image.size.height; 
    CGRect imageFrame = CGRectMake(myFrame.size.width/2, yImage, self.image.size.width, self.image.size.height); 
    [self.image drawInRect:imageFrame]; 

    //UILabel number of seats 
    [self drawString:[NSString stringWithFormat:@"%li", (long)self.numberSeats] 
      withFont:self.numberSeatsFont 
      andColor:self.numberSeatsColor 
      aligment: NSTextAlignmentRight 
       inRect:CGRectMake(0, yImage, imageFrame.origin.x, self.image.size.height)]; 

    //UILabel Title 
    UIFont *titleFont = [UIFont systemFontOfSize:20]; 
    UIColor *titleColor = [UIColor redColor]; 
    [self drawString:self.title 
      withFont:titleFont 
      andColor:titleColor 
      aligment: NSTextAlignmentCenter 
       inRect:CGRectMake(0, myFrame.size.height/2, myFrame.size.width, myFrame.size.height/2)]; 
} 

- (void) drawString: (NSString*) s 
      withFont: (UIFont*) font 
      andColor: (UIColor *)color 
      aligment: (NSTextAlignment) alignment 
      inRect: (CGRect) contextRect { 

    CGFloat fontHeight = font.pointSize; 
    CGRect textRect = CGRectMake(0, contextRect.origin.y, contextRect.size.width, fontHeight); 
    NSMutableParagraphStyle* p = [NSMutableParagraphStyle new]; 
    p.alignment = alignment; 
    [s drawInRect:textRect withAttributes:@{NSFontAttributeName: font, 
              NSForegroundColorAttributeName: color, 
              NSParagraphStyleAttributeName: p}]; 
} 
@end 

在谷歌搜索後,我發現這個職位:IBDesignable View Rendering times out我嘗試做覆蓋initWithFrame,initWithCoder但它仍然無法正常工作。

回答

0

基本上,使用DrawRect()方法進行實時渲染的目的是錯誤的概念。 Apple爲此提供了一個單獨的方法(用於Live渲染目的)「 - (void)prepareForInterfaceBuilder {}」。 但是,在這種情況下,您無法從IB設置UIFont屬性。但你可以設置UIcolor。

Sample Project

+0

我可以在[蘋果]參見(https://developer.apple.com/library/ios/recipes/xcode_help-IB_objects_media/Chapters/CreatingaLiveViewofaCustomObject.html)'如果你需要爲創建代碼一個只能在Interface Builder中運行的自定義視圖,從prepareForInterfaceBuilder方法中調用該代碼,但在調試後,它不會運行到此方法中,以至於無法運行 – l3adl3oy