簡體   English   中英

單擊按鈕即可將子視圖動態添加到主視圖中

[英]Adding subviews dynamically into the main view on button click

我想創建一個包含添加按鈕的主視圖。

每次單擊添加按鈕時,都必須在主視圖中添加一個子視圖。該子視圖存在於另一個包含關閉按鈕的類中,單擊關閉按鈕時,子視圖類會通過委托函數和特定控件通知主視圖。子視圖霧從主視圖中刪除。

其余子視圖必須在主視圖中重新定位。

我希望將子視圖以矩陣形式(2xN)矩陣添加到主視圖中。 那是在一行中有n個列的2個子視圖。

我已經實現了兩種相同的方法,但是子視圖沒有重新定位。

方法1:

    - (IBAction)btnAddView:(id)sender
    {

        if ((count%2)==0)
        {
            NewSubView *subView = [[NewSubView alloc]initWithFrame:CGRectMake(10, 10+       (i*120), 100, 100) andDelegate:self];
           // [self.view addSubview:subView];
            [arr addObject:subView];
            i++;

        }
        else if ((count%2)==1)
        {
            NewSubView *subView = [[NewSubView alloc]initWithFrame:CGRectMake(120, 10+(j*120), 100, 100) andDelegate:self];
           // [self.view addSubview:subView];
            [arr addObject:subView];
            j++;
        }

         count = count+1; 

        for (int x=0; x<[arr count]; x++) {
            [self.view addSubview:[arr objectAtIndex:x]];
        }


    self.lblCount.text = [ NSString stringWithFormat:@"count: %d",count];

}


//  the delegate function for deleting the view is as follows  


- (void) handleDelegate:(id)sender
{
    int deletedIndex;
    for (int val=0; val<[arr count]; val++) {
        if([[arr objectAtIndex:val] isEqual:sender])
            deletedIndex =val;
    }
    dupArray =[[NSMutableArray alloc]initWithArray:arr];
    [arr removeObjectAtIndex:deletedIndex];
    [sender removeFromSuperview];
    count--;
    self.lblCount.text = [ NSString stringWithFormat:@"count: %d",count];


    if ((deletedIndex%2)==0)
        i=deletedIndex/2;
    if ((deletedIndex%2)==1)
        j--;



}

方法2:

   - (IBAction)btnAddView:(id)sender
   {
     int modifiedColValue= 10+(colValue*120);

        if (modifiedColValue<320)
        {

            NewSubView *subView = [[NewSubView alloc]initWithFrame:CGRectMake(rowValue, modifiedColValue, 100, 100) andDelegate:self];
            [arr addObject:subView];

            colValue++;
        }
        else if (modifiedColValue>320)
        {
            rowValue=10;
            [self btnAddView:sender];
            colValue++;
        }

        count++;
        for (int x=0; x<[arr count]; x++)
        {
            [self.view addSubview:[arr objectAtIndex:x]];
        }

    }

我如何重新定位其余的子視圖,其中count是子視圖的數量,320是主視圖的寬度。

我相信您正在尋找的答案是UICollectionView。 您可能會發現本教程很有幫助: http : //skeuo.com/uicollectionview-custom-layout-tutorial

暫無
暫無

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

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