Извлечение цены SKProduct в метку ячейки UICollectionView - PullRequest
1 голос
/ 19 февраля 2020

Я столкнулся с проблемой, когда при извлечении цены локали SKProduct в label.text моего UICollectionView, он отображается правильно, однако цены меняются в разных ярлыках в зависимости от скорости загрузки страницы.

TopUpViewController (UICollectionView) -> TopUpMoneyCell (MoneyLabel)

Есть идеи, как решить эту проблему? В настоящее время я звоню SKProduct в TopUpMoneyCell. У меня в приложении есть массив из 4 продуктов, каждый из которых имеет свое значение.

Должен ли я вместо этого вызывать его из TopUpViewController? Если да, то как мне перенести данные, полученные из TopUpViewController, в TopUpMoneyCell?

Редактировать 1: добавлен макет пользовательского интерфейса, еще раз спасибо за комментарии.

Просмотр макета пользовательского интерфейса

Ответы [ 3 ]

0 голосов
/ 20 февраля 2020

Не видя никакого кода, немного сложно увидеть, что вы делаете, но, похоже, вы захотите, чтобы ваш TopUpViewController соответствовал протоколу UICollectionViewDataSource (https://developer.apple.com/documentation/uikit/uicollectionviewdatasource?language=objc)

Тогда вы могли бы реализовать что-то вроде следующего:


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell* cell = [self.testCollectionView dequeueReusableCellWithReuseIdentifier:@"SomeReuseID"
                                                                                    forIndexPath:indexPath];

    // set your custom labeling on the cell here (you probably have a subclass)

    return cell;
}

Не забудьте указать UICollectionView, что использовать для его источника данных.

Из того, что вы описываете, это Похоже, ваши ячейки запрашивают какой-либо источник данных напрямую, поэтому, когда UICollectionView выбирает повторное использование ячейки, метки расположены не в том порядке, в котором вы собираетесь.

0 голосов
/ 22 февраля 2020

Хорошо, мне удалось решить мою проблему. Буду признателен, если кто-нибудь может помочь упростить мой код :) Ниже приведен фрагмент кода.

#import "TopUpMoneyCell.h"
#import "TopUpMoneyModel.h"
#import <StoreKit/StoreKit.h>

@interface TopUpMoneyCell() <SKProductsRequestDelegate>
@property (nonatomic,strong) NSString *purchID;
@property (nonatomic,strong) NSArray *products;
@property (nonatomic,strong) NSArray *productID;
@property (nonnull,strong) IAPCompletionHandle handle;
@property (strong,nonatomic) SKProductsRequest *request;
@property (strong,nonatomic) SKProduct *firstProduct;
@property (strong,nonatomic) SKProduct *secondProduct;
@property (strong,nonatomic) SKProduct *thirdProduct;
@property (strong,nonatomic) SKProduct *fourthProduct;
@property (strong,nonatomic) NSString *firstProductPrice;
@property (strong,nonatomic) NSString *secondProductPrice;
@property (strong,nonatomic) NSString *thirdProductPrice;
@property (strong,nonatomic) NSString *fourthProductPrice;
@property (nonatomic, weak) UILabel *firstPriceLabel;
@property (nonatomic, weak) UILabel *secondPriceLabel;
@property (nonatomic, weak) UILabel *thirdPriceLabel;
@property (nonatomic, weak) UILabel *fourthPriceLabel;
@end

@implementation AQTopUpMoneyCell

- (UILabel *)priceLabel {
    if (!_priceLabel) {
        UILabel *label = [[UILabel alloc] init];
        _priceLabel = label;
        label.textAlignment = NSTextAlignmentCenter;
        label.text = @"";
    }
    return _priceLabel;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self productsInfoRequest];
        [self cnyLabel];
    }
    return self;
}

- (void)productsInfoRequest {
                _productID = [NSArray arrayWithObjects:@"100",@"200",@"300",@"400", nil];
               SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithArray:_productID]];
                request.delegate = self;
                [request start];
    }

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
    {
        NSSortDescriptor *mySortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"price" ascending:NO];
        NSMutableArray *_productsAvailable = [[NSMutableArray alloc] initWithArray:response.products];
        [_productsAvailable sortUsingDescriptors:[NSArray arrayWithObject:mySortDescriptor]];

        self.firstProduct = response.products[0];
        self.secondProduct = response.products[1];
        self.thirdProduct = response.products[2];
        self.fourthProduct = response.products[3];

        NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
        [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
        [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
        [numberFormatter setLocale:_firstProduct.priceLocale];
        self.firstProductPrice = [numberFormatter stringFromNumber:_firstProduct.price];
        self.secondProductPrice = [numberFormatter stringFromNumber:_secondProduct.price];
        self.thirdProductPrice = [numberFormatter stringFromNumber:_thirdProduct.price];
        self.fourthProductPrice = [numberFormatter stringFromNumber:_fourthProduct.price];

        static int counter = 0;
        if (counter == 4) {
            counter = 0;
        }
        if ( [_productsAvailable count] > 0){
            if (_indexPath.row == 0)
            {[self.priceLabel setText:_firstProductPrice];}
            if (_indexPath.row == 1)
            {[self.priceLabel setText:_secondProductPrice];}
            if (_indexPath.row == 2)
            {[self.priceLabel setText:_thirdProductPrice];}
            if (_indexPath.row == 3)
            {[self.priceLabel setText:_fourthProductPrice];}
            counter++;
        }
    }

#pragma mark - SKProductsRequestDelegate
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
#if DEBUG
    NSLog(@"log-IAP> request -> failedWithError: %@", error);
    [SVProgressHUD showErrorWithStatus:@"Request timed out. Try again later."];
#endif
}

- (void)requestDidFinish:(SKRequest *)request{
#if DEBUG
    NSLog(@"log-IAP> requestDidFinish?");
#endif
}


- (void)setIndexPath:(NSIndexPath *)indexPath {
    _indexPath = indexPath;
    NSString *imageName = [NSString stringWithFormat:@"touupbg_%ld",indexPath.row];
    self.bgImageV.image = [UIImage imageNamed:imageName];
    if (indexPath.row == 0) {
        [self.bgImageV mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(kScale(367*scale));
            make.width.equalTo(kScale(308*scale));
        }];
    } else if (indexPath.row == 1) {
        [self.bgImageV mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(kScale(380*scale));
            make.width.equalTo(kScale(308*scale));
        }];
    }else if (indexPath.row == 2) {
        [self.bgImageV mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(kScale(373*scale));
            make.width.equalTo(kScale(316*scale));
        }];
    }else if (indexPath.row == 3) {
        [self.bgImageV mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(kScale(403*scale));
            make.width.equalTo(kScale(308*scale));
        }];
    }else if (indexPath.row == 4) {
        [self.bgImageV mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(kScale(400*scale));
            make.width.equalTo(kScale(308*scale));
        }];
    }else if (indexPath.row == 5) {
        [self.bgImageV mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(kScale(401*scale));
            make.width.equalTo(kScale(317*scale));
        }];
    }
}
@end
0 голосов
/ 20 февраля 2020

Взгляните на переопределение функции prepareForReuse() в вашем TopUpMoneyCell. В этой функции отмените любые асинхронные вызовы, которые вы, возможно, начали загружать цену.

...