簡體   English   中英

NSMutableArray為圖像創建問題

[英]NSMutableArray creates issue for images

我有一個帶有字典的數組。 每個字典都包含UIImage和String值。

但是當我嘗試使用刪除對象時

[arr removeObjectAtIndex:button.tag];

那么它只會減少計數,但不會刪除圖像(對象)。 因此,嘗試刪除時我的圖像重疊。

當我嘗試在數組中添加對象時,也會產生問題

[arr insertObject:dict atIndex:0];

因此,我使用了[_postObj.arr_images addObject:dict]; 代替insertObject

幫我解決這個問題

對象使用引用計數, NSMutableArrayUIImageView都將保留 UIImage對象。

這意味着將其從數組中刪除不會自動將其從UIImageView刪除,並且您必須同時將其從兩個對象中明確刪除:

[arr removeObjectAtIndex:button.tag];
_imageView.image = nil;

問題出在您的UIImageView框架設置中。 請嘗試使用以下代碼(未經我自己測試),看看是否能為您解決問題。 基本上,我正在根據先前圖像的寬度調整圖像的X位置。

CGFloat imageXM = 5.0;
CGFloat imageXPos = 0;

for (UIImage *image in arr_images) {
    CGRect imageFrame = CGRectMake(imageXPos + imageXM, 0.0, image.size.width, image.size.height);
    imageXPos = imageXPos + image.size.width;

    UIImageView *imageView = [[UIImageView alloc] initWithFrame:imageFrame];

    imageView.contentMode = UIViewContentModeScaleAspectFit;
    imageView.image = image;
    [scl addSubview:imageView];
}

如你的代碼

[picker dismissViewControllerAnimated:YES completion:^{
        [arr_images insertObject:chosenImage atIndex:0];
        [self scrollImages_Setup2];

    }];

[arr_images insertObject:chosenImage atIndex:0]; 這意味着您僅需要一張圖像即可在滾動視圖中顯示。 那么為什么要循環:

-(void)scrollImages_Setup2
{    
    for (int k=0; k<arr_images.count; k++) {

        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake((CGRectGetWidth(scl.frame) * k) + CGRectGetWidth(scl.frame), 0, CGRectGetWidth(scl.frame), CGRectGetHeight(scl.frame))];

        imageView.contentMode = UIViewContentModeScaleAspectFit;
        imageView.image=[arr_images objectAtIndex:k] ;
        [scl addSubview:imageView];
    }

    scl.contentSize = CGSizeMake((CGRectGetWidth(scl.frame) * arr_images.count)+CGRectGetWidth(scl.frame), CGRectGetHeight(scl.frame));

}

您只需要正確的代碼即可顯示圖像。 您無需滾動視圖即可僅顯示一張圖像。 我認為您不清楚您想要什么。

您關於由於循環而覆蓋圖像的問題。 因此,當您顯示單個圖像時,請刪除循環。 請刪除scrollview contentSize,因為在數組中添加多個圖像時image_array會增加,並且size寬度會很大。 因此也要刪除arr_images.count。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM