2013-09-01 4 views
1

Я новичок в объективе-c, поэтому, пожалуйста, несите меня. Я работаю над некоторым кодом в качестве упражнения, начиная со Стэнфордского курса «Программирование для iPhone/iPad» зимой 2013 года. В принципе, мне нужно сделать изображение как кнопку для UIControlStateNormal кнопки. К сожалению, я еще не могу опубликовать фотографии, чтобы переполнять стек, но когда я пытаюсь установить изображение на кнопке для обычного UIControlState, изображения для кнопок повсюду и больше, чем фактические кнопки. Для других параметров UIControlState кнопки с изображением ведут себя так, как ожидалось. Всего всего 16 кнопок.Objective-C setImage forState: UIControlStateNormal не правильно форматирует изображение

Я не уверен, что я делаю неправильно. У меня есть изображения кнопок, которые устанавливаются в цикле for в ViewController приложения в методе, называемом «updateUI». Вот код:

#import "CardGameViewController.h" 
#import "PlayingCardDeck.h" 
#import "CardMatchingGame.h" 

@interface CardGameViewController() 
@property (weak, nonatomic) IBOutlet UILabel *scoreLabel; 
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *cardButtons; 
@property (weak, nonatomic) IBOutlet UILabel *flipsLabel; 
@property (nonatomic) int flipCount; 
@property (strong, nonatomic)CardMatchingGame* game; 
@property (weak, nonatomic) IBOutlet UILabel *lastFlipLabel; 
@property (weak, nonatomic) NSArray *lastFlip; 
@property (weak, nonatomic) IBOutlet UISegmentedControl *gameControl; 
@end 

@implementation CardGameViewController 
//lazy instantiation of the game 
-(CardMatchingGame *)game 
{ 
    if(!_game) 
    { 
     _game = [[CardMatchingGame alloc] initWithCardCount:self.cardButtons.count usingDeck:[[PlayingCardDeck alloc]init]]; 
    } 
    return _game; 
} 
//set the properties of the card buttons 
-(void)setCardButtons:(NSArray *)cardButtons 
{ 
    _cardButtons = cardButtons; 
    [self updateUI]; 
} 
//method to update the UI 
-(void)updateUI 
{ 
    UIImage* cardback = [UIImage imageNamed:@"cardback.png"];//loads in the pic for the cardback 
    //go through all the card buttons and update 
    for(UIButton *cardButton in self.cardButtons) 
    { 
     Card* card = [self.game cardAtIndex:[self.cardButtons indexOfObject:cardButton]];//get the card 
     [cardButton setTitle:card.contents forState:UIControlStateSelected]; 
     [cardButton setTitle:card.contents forState:UIControlStateSelected|UIControlStateDisabled]; 
     cardButton.selected = card.isFaceUp; 
     cardButton.enabled = !card.isUnplayable; 
     cardButton.alpha = card.isUnplayable ? 0.2 : 1.0; 
     if(cardback) 
     { 
      [cardButton setImage:cardback forState:UIControlStateNormal]; 
     } 
     [cardButton setTitle:@"" forState:UIControlStateNormal]; 
     self.scoreLabel.text = [NSString stringWithFormat:@"Score: %d",self.game.score]; 
    } 
    self.lastFlip = self.game.lastFlip;//get the result of the last flip from the model 
    [self.gameControl setTitle:@"2-Card \n Game" forSegmentAtIndex:0]; 
    [self.gameControl setTitle:@"3-Card \n Game" forSegmentAtIndex:1]; 
} 
- (IBAction)flipCard:(UIButton *)sender 
{ 
    [self.game flipCardAtIndex:[self.cardButtons indexOfObject:sender]]; 
    self.flipCount++; 
    [self updateUI]; 
} 
//setter for flipCount, update to the UI 
-(void)setFlipCount:(int)flipCount 
{ 
    _flipCount = flipCount; 
    self.flipsLabel.text = [NSString stringWithFormat:@"Flips: %d",self.flipCount]; 
} 
//setter for lastFlips, update to the UI 
-(void)setLastFlip:(NSArray *)lastFlip 
{ 
    _lastFlip = lastFlip; 
    //append the last flips together to display the status 
    NSString* cardString = [[NSString alloc]init]; 
    cardString = [self.lastFlip componentsJoinedByString:@" and "]; 
    if(self.lastFlip.count==1 && ![cardString isEqualToString:@""]) 
    { 
     self.lastFlipLabel.text = [NSString stringWithFormat:@"You just flipped the %@", cardString]; 
    } 
    else if(self.lastFlip.count!=1 && self.game.lastMatch) 
    { 
     self.lastFlipLabel.text = [NSMutableString stringWithFormat:@"You just matched the %@ \n for %d points!",cardString, self.game.lastScore]; 
    } 
    else if(self.lastFlip.count!=1 && !self.game.lastMatch) 
    { 
     self.lastFlipLabel.text = [NSString stringWithFormat:@"Oohh, sorry the %@ don't match. %d points for you!", cardString, self.game.lastScore]; 
    } 
} 
//reset the game 
- (IBAction)resetGame:(UIButton *)sender 
{ 
    self.game = [[CardMatchingGame alloc]initWithCardCount:self.cardButtons.count usingDeck:[[PlayingCardDeck alloc]init]]; 
    [self.game reset]; 
    self.lastFlipLabel.text = @"";//reset the text so it's blank 
    self.flipCount = 0; 
    [self updateUI]; 
} 


@end 
+0

Кроме того, я запускаю это на симуляторе iOS 6.1. – themantalope

+0

Возможно, это противоречит вашему типу '@" "'? – Mundi

ответ

1

Попробуйте отключить автоматическую компоновку - в правой панели вашего раскадровки в Xcode.

+0

Woo! Это сработало, но теперь у меня другая проблема. Изображение, которое я установил для UIControlStateNormal, также появляется после нажатия кнопки. То, что должно отображаться, представляет собой строку, представляющую карту (например, «A ♣» и т. Д.). Если я установил изображение для UIControlStateNormal, почему он также появляется в UIControlStateSelected? – themantalope

+0

отличная - отметьте как правильно пожалуйста. Отображается ли изображение, когда вы нажимаете его вообще? Затем возвращается обратно к controlstatenormal? – DogCoffee

+0

Да, изображение появляется, но оно появляется как для ControlStateNormal, так и после выбора кнопки, которое я понимаю из API, чтобы быть UIControlStateSelected. Что должно произойти, так это то, что после нажатия кнопки «карта» должна «перевернуться», чтобы открыть строку, которая представляет эту карту. У карт по-прежнему есть правильные строки, назначенные им, но изображение, которое я установил с этой строкой: [cardButton setImage: cardback forState: UIControlStateNormal]; также появляется после нажатия кнопки. – themantalope

Смежные вопросы