動態添加UIButton控件,通過設置tag值實現點擊不同的UIButton控件做出不同的反應


在上一篇博文《在滾動視圖里添加圖像視圖,在圖像視圖里添加按鈕控件》的基礎上做了小小的改動。

》》點擊button1》》

》》點擊button2》》

需要改寫兩個地方:

@synthesize scrollView = _scrollView;

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 配置 UIImageView 對象
    UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"1.png"]];
    imgView.userInteractionEnabled = YES;  // UIImageView 的 userInteractionEnabled 屬性默認 "NO",因此默認情況下,添加在 UIImageView 中的 UIButton 將不發生觸摸事件
    
    // 配置並添加 UIButton 對象
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button1.frame = CGRectMake(100, 80, 40, 40);
    [button1 setTitle:@"Button1" forState:UIControlStateNormal];
    
    button1.tag = 100;      // 1、分別設置tag
    
    [button1 addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
    [imgView addSubview:button1];
    
    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button2.frame = CGRectMake(200, 80, 40, 40);
    [button2 setTitle:@"Button2" forState:UIControlStateNormal];
    
    button2.tag = 200;      // 1、分別設置tag
    
    [button2 addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
    [imgView addSubview:button2];
    
    // 添加 UIImageView 對象
    [self.scrollView addSubview:imgView];
    
    // 配置 UIScrollView 對象
    self.scrollView.indicatorStyle = UIScrollViewIndicatorStyleBlack;
    self.scrollView.scrollEnabled = YES;
    self.scrollView.clipsToBounds = YES;
    self.scrollView.contentSize = CGSizeMake(imgView.frame.size.width, imgView.frame.size.height);
    
}

- (IBAction)button:(id)sender
{
    UIButton *button = (UIButton *)sender;
    
    // 2、通過tag進行選擇對應的操作
    if (button.tag == 100) {
        [self performSegueWithIdentifier:@"SeguePush" sender:self];
    } else {
        NSLog(@"button2");
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM