带动态标签和按钮的UIscrollview

时间:2015-07-16 14:10:16

标签: ios objective-c uiscrollview

我有按钮和标签的滚动视图。

我为每个按钮列和行确定位置。

按钮示例:

input

我希望按钮能够居中对齐。我怎么能这样做?

您可以在此处显示图片:http://s28.postimg.org/jy4i3a2nh/Capture_d_cran_2015_07_16_16_46_00.png

1 个答案:

答案 0 :(得分:0)

使用UIScrollView - 更新

你需要保存对NSMutableArray中所有按钮的引用,或者只是对按钮标题的引用,以及对按钮居中的参考:

@interface yourViewController ()

@property (nonatomic, strong) UIButton *centeredButon;
@property (nonatomic, strong) UIScrollView *scrollView;

@end;

- (void)viewDidLoad {
[super viewDidLoad];
    //initialize the array
    self.buttonTitles = [[NSMutableArray alloc] init];

    // set all your button titles here somehow

    // create your views here.
    // i suggest you dont set their frames here. self.view has not the correct frame at this time

    // do other stuff you need here
}

我们覆盖viewDidLayoutSubviews以正确设置帧

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    for (UIView *view in self.scrollView.subviews) {
        if (view == self.centeredButton) {
            view.frame = [self centerFrameForButton:button];
        } else {
            view.frame = [self frameForView:view];
            // i dunno how you set or get the element.line and element.column but this might need to be evaluated
        }
    }
}

- (void)setCenteredButton:(UIButton *)centeredButton {
    if (_centeredButton != centeredButton) {
        // if you want to animate the centering, you can do it here
        centeredButton.frame = [self centerFrameForButton:centeredButton];
        //if we had a centered button before, set it back to its original position
        if (_centeredButton) {
            _centeredButton.frame = [self frameForView:_centeredButton];
        }

        // now we update the variable
        _centeredButton = centeredButton;
    }
}

- (CGRect)frameForView:(UIView *)view {
    //use your logic to find the view frame.
    //to find its position properly, you could just get its index from the scrollView.subviews:
    NSInteger viewIndex = [self.scrollView.subviews indexOfObject:view];
    // find out its position and return the frame
    return CGRectMake([[element column] doubleValue]*60,[[element line] floatValue]*40,50, 30);
}

- (CGRect)centerFrameForButton:(UIButton *)button {
    CGFloat originX = (self.scrollView.bounds.width - button.bounds.size.width) / 2.f;
    CGFloat originY = (self.scrollView.bounds.height - button.bounds.size.height) / 2.f;
    CGRect centerFrame = CGRectMake(originX, originY, self.button.bounds.size.width, self.button.bounds.size.height);
    return centerFrame;
}