我一直在關注CS193P Stanford iOS開發講座,在第二個作業「Set」中,我無法弄清楚我的程序在按鈕上顯示一個屬性字符串時出了什麼問題。出於某種原因,當我的字符串嘗試顯示3個字符時,最終顯示爲1個大字符和3個隨機的其他字符。當我只想要那裏有紅色,綠色和藍色字符時,許多字符顯示爲黑色。如果有人能夠構建這個項目並幫助我弄清楚發生了什麼,我將不勝感激。我花了大約4個小時試圖調試這個。來源是 https://github.com/zhumatthew/MatchSet爲什麼我的屬性字符串顯示奇怪?
問題出在設置視圖控制器下的標籤欄中的第二個選項卡。
謝謝。
http://postimg.org/image/gs7qley3r/
#import "SetViewController.h"
#import "SetCardDeck.h"
#import "SetCard.h"
@interface SetViewController()
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *cardButtons;
@end
@implementation SetViewController
@synthesize deck = _deck;
- (Deck *)deck {
if (!_deck) _deck = [[SetCardDeck alloc] init];
return _deck;
}
- (void)updateUI {
[super updateUI];
for (UIButton *cardButton in self.cardButtons) {
UIColor *foregroundColor;
UIColor *strokeColor;
SetCard *card = (SetCard *)[self.game cardAtIndex:[self.cardButtons indexOfObject:cardButton]];
NSString *string = [[NSString alloc] init];
for (int i = 0; i < card.number; i++) {
string = [NSString stringWithFormat:@"%@%@", string, card.symbol];
}
if ([card.color isEqualToString:@"R"]) {
foregroundColor = [UIColor redColor];
} else if ([card.color isEqualToString:@"G"]) {
foregroundColor = [UIColor greenColor];
} else if ([card.color isEqualToString:@"B"]) {
foregroundColor = [UIColor blueColor];
}
strokeColor = [foregroundColor copy];
if ([card.shading isEqualToString:@"S"]) {
foregroundColor = [foregroundColor colorWithAlphaComponent:1];
} else if ([card.shading isEqualToString:@"H"]) {
foregroundColor = [foregroundColor colorWithAlphaComponent:0.3];
} else if ([card.shading isEqualToString:@"O"]) {
foregroundColor = [foregroundColor colorWithAlphaComponent:0];
}
NSAttributedString *mat = [[NSAttributedString alloc] initWithString:string attributes:@{NSForegroundColorAttributeName:foregroundColor,NSStrokeWidthAttributeName:@-5,NSStrokeColorAttributeName:strokeColor}];
[cardButton setAttributedTitle:mat forState:UIControlStateNormal];
CGFloat red;
CGFloat green;
CGFloat blue;
CGFloat alpha;
[foregroundColor getRed:&red green:&green blue:&blue alpha:&alpha];
NSLog(@"red:%f green:%f blue:%f alpha:%f index:%d",red,green,blue,alpha,[self.cardButtons indexOfObject:cardButton]);
[strokeColor getRed:&red green:&green blue:&blue alpha:&alpha];
NSLog(@"red:%f green:%f blue:%f alpha:%f ",red,green,blue,alpha);
NSLog(@"%@",[mat string]);
cardButton.selected = card.isFaceUp;
cardButton.enabled = !card.isUnplayable;
if (card.isFaceUp) {
[cardButton setBackgroundColor:[UIColor lightGrayColor]];
} else {
[cardButton setBackgroundColor:[UIColor whiteColor]];
}
}
}
@end
我們可以在這裏看到一些代碼,也許有一些截圖,所以我們不必編譯和篩選代碼? – Undo
@MatthewZhu檢查我的答案NSAttributeString與另一編碼..嘗試的代碼,讓我從這個鏈接http://stackoverflow.com/questions/13579209/two-colors-for-uilabel-text/13579318#13579318 –