Search code examples
iosobjective-cuitableviewuiscrollviewuilabel

Horizontal scroll for uilabel?


How can i write code for making horizontal scroll for the array of uilabel

Example:

 NSArray *tagsArray = [NSJSONSerialization JSONObjectWithData:someData options:kNilOptions error:&error];
if ([tagsArray count]>0) {
for (int i=0; i<[tagsArray count]; i++) {
CGRect ansCountValueRectangle13 = CGRectMake(80*i+10,110,80,30);
UILabel  *_tagsValue = [[UILabel alloc] initWithFrame:ansCountValueRectangle13];
    _tagsValue.clipsToBounds=YES;
    _tagsValue.tag=250;
    _tagsValue.text = [tagsArray objectAtIndex:i];
    _tagsValue.layer.cornerRadius=15.0;
    _tagsValue.backgroundColor = [UIColor orangeColor];
    _tagsValue.textAlignment = NSTextAlignmentCenter;
    _tagsValue.textColor=[UIColor whiteColor];
    _tagsValue.font = [UIFont boldSystemFontOfSize:16];
    [testing addSubview: _tagsValue];
}
}

for this i have to add UIScrollView ,these code written inside of tableViewCell and i want each tableview row have Horizontal Scroll with UILabel

enter image description here


Solution

  • What you have to do is add the label to scrollView and add scrollView to table view cell content view:

    // You have to change the scroll frame to match your requirements
        UIScrollView *sv = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0, 10.0, self.view.bounds.size.width, 35)]; 
        sv.backgroundColor = [UIColor grayColor]; // I've added color to see when the scroll view is layout
        float svWidth = 10; //Margin to content view width (feel fee to change it or remove it)
        if ([tagsArray count]>0) {
            for (int i=0; i<[tagsArray count]; i++) {
                CGRect ansCountValueRectangle13 = CGRectMake(80*i+10,2,80,30);
                UILabel  *_tagsValue = [[UILabel alloc] initWithFrame:ansCountValueRectangle13];
                _tagsValue.clipsToBounds=YES;
                _tagsValue.tag=250;
                _tagsValue.text = [tagsArray objectAtIndex:i];
                _tagsValue.layer.cornerRadius=15.0;
                _tagsValue.backgroundColor = [UIColor orangeColor];
                _tagsValue.textAlignment = NSTextAlignmentCenter;
                _tagsValue.textColor=[UIColor whiteColor];
                _tagsValue.font = [UIFont boldSystemFontOfSize:16];
                svWidth += 80+10;
                [sv addSubview:_tagsValue];
                // I don't know what is testing, you have to add the labels to scrollView
                //[testing addSubview: _tagsValue];
            }
            // Set the content size of the scroll view, feel free to tweak it
            [sv setContentSize:CGSizeMake(svWidth, 35)];
            // Add scroll view to your cell, I've added it to contentView but maybe you want to add it to some subview
            [cell.contentView addSubview:sv];
    
        }