Search code examples
iosobjective-cxcodeuiscrollviewuibutton

Custom UIButton in UIscrollview


I am using xcode 4.6 to develop an app. Here i want to add UIButton programmatically to UIscrollview. This is the code i follow.

UIButton *bt =[[UIButton alloc]initWithFrame:frame];
bt=[UIButton buttonWithType:UIButtonTypeCustom];
[bt setTitle:@"Custom Button" forState:UIControlStateNormal];
[bt addTarget:self action:@selector(userTappedOnLink:) forControlEvents:UIControlEventTouchUpInside];
bt.backgroundColor = [UIColor grayColor];
bt.titleLabel.textColor=[UIColor blueColor];
[self.mainscrollview addSubview:bt];
[self.mainscrollview bringSubviewToFront:bt];

Now the problem is that Button gets disappeared (technically its textcolor becomes white) on click. I checked keeping UIscrollview color to red that th button was still in the view but i cant get the reason why its text color changed and how do i undo dis. Basically I wan to create a clickable link using UIbutton. I know uitextview approach (datadetectortype) but its of no use as i want to show different text in the label for the link and the actual link.

Note: The textcolor doesnt change back to blue and remains white only.

Thanks in advance.


Solution

  • Try the below code

    UIButton *bt =[UIButton buttonWithType:UIButtonTypeCustom];
    bt.frame = CGRectMake(50.0, 50.0, 100.0, 50.0);
    [bt setTitle:@"Custom Button" forState:UIControlStateNormal];
    [bt addTarget:self action:@selector(userTappedOnLink:) forControlEvents:UIControlEventTouchUpInside];
    bt.backgroundColor = [UIColor grayColor];
    bt.titleLabel.textColor=[UIColor blueColor];
    [self.scrollTest addSubview:bt];
    
    -(void)userTappedOnLink:(UIButton*)sender
    {
         NSLog(@"Test  ..");
    
        [self performSelector:@selector(changeBtnTextColor:) withObject:sender afterDelay:1.0];
    }
    
    -(void)changeBtnTextColor:(UIButton*)btn
    {
      btn.titleLabel.textColor=[UIColor blueColor];
    }
    

    hope it will work for you.