Relativelayout or LinearLayout in ios iphone development?

前端 未结 6 663
再見小時候
再見小時候 2021-02-08 15:23

I want to add a subview in the top of my view, I have to recalculate the origin y value for all of other views and re-position them to leave space for the new added view.

<
6条回答
  •  忘了有多久
    2021-02-08 15:38

    It's not much work to subclass UIView to make sense of methods like -(void)addView:toRightOfView: etc. You could do this as you go, porting only the methods you need. You could then call these in your override of layoutSubviews as Benjamin indicates.

    Views can be built using IB or they can be written programmatically; Android scores well here in making layouts readable and you can bring that benefit to iOS views created programmatically. That there are few iOS devices means beyond readability there are not (yet?) many practical benefits to this pattern.

    NB. A "XIB" file is an XML file. Open it up in your favourite text editor and take a look.

    ** EDIT.

    Here's a quick example I knocked up. It has not been tested but some thing like this will work in your subclass of UIView (call it UIRelativeView perhaps).

    - (void) addSubview:(UIView *) viewOne
       toRightOfSubview:(UIView *) viewTwo
    {
      if (viewTwo == nil ||
          [self.subviews contains:viewTwo] == NO)
      {
        [self addSubview:viewOne];
      }
      else
      {
        CGRect frameTwo = viewTwo.frame;
        CGPoint originOne = CGPointMake(frameTwo.origin.x + frameTwo.size.width,
                                        frameTwo.origin.y);
    
        CGRect frameOne = CGRectZero;
        frameOne.origin = originOne;
        frameOne.size = viewOne.frame.size;
    
        [viewOne setFrame:frameOne];
        [self addSubview:viewOne];
      }
    }
    
    - (void) moveSubview:(UIView *) viewOne
        toRightOfSubview:(UIView *) viewTwo
    {
      if (viewTwo == nil ||
          [self.subviews contains:viewTwo] == NO)
      {
        [self addSubview:viewOne];
      }
      else if ([self.subviews contains:viewOne] == NO)
      {
        [self addSubview:viewOne toRightOfSubview:viewTwo];
      }
      else
      {
        CGRect frameTwo = viewTwo.frame;
        CGPoint originOne = CGPointMake(frameTwo.origin.x + frameTwo.size.width,
                                        frameTwo.origin.y);
    
        CGRect frameOne = CGRectZero;
        frameOne.origin = originOne;
        frameOne.size = viewOne.frame.size;
    
        [viewOne setFrame:frameOne];
      }
    }
    

提交回复
热议问题