【问题标题】:How to add buttons dynamically along with the scrollview in iPhone SDK?如何在 iPhone SDK 中与滚动视图一起动态添加按钮?
【发布时间】:2011-01-18 13:18:58
【问题描述】:

在我的 iPhone 应用程序中,我必须将按钮与滚动视图一起动态放置。

现在我需要让按钮单击事件与每个按钮相关联,并对每个按钮单击执行特定操作。

我的按钮有一个 ASCII 艺术的标题。因此,在这种情况下,创建通用 IBAction 并根据按钮标题执行操作将不是一个简单的选择。

还有哪些其他选择?

如何将按钮点击事件与特定按钮相关联?

【问题讨论】:

    标签: iphone cocoa-touch ios4 uiscrollview uibutton


    【解决方案1】:

    我认为你可以使用 UIView 的 tag 属性。

    我的程序可能如下所示。

    - (NSInteger)encodeTagForButtonID:(NSString *)buttonID;
    - (NSString *)decodeButtonIDFromEncodedTag:(NSInteger)tag;
    

    当我创建一个 UIButton 时,我将按钮的 ID 编码为 tag。 buttonID 可能是有意义的,或者它只是一个整数,就像定义的值一样。 action的签名可以是这样的形式:-(void)buttonAction:(id)sender;,我可以从sender中获取tag的值>.

    编辑:

    例如,在 UITableView 的数据源方法中。

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        static NSString *identifier = @"Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
               /// new an autoreleased cell object
        }
    
        // Configure cell
        cell.tag = [self encodeTagWithIndexPath:indexPath];
    
        return cell;
    }
    

    当我触摸这个单元格时,我从标签中检索 indexPath。

    UIButton 是 UIView 的子类,所以它也有 tag。例如,我制作了一个自定义 actionSheet,它包含一个 UIButtons 列表。当我按下 UIButton 时,我需要知道我按下了哪个按钮。所以,我将行信息分配给标签。

    NSArray *buttonListInActionSheet = ....; ///< UIButton array, a button per row.
    for (int idxBtn = 0; idxBtn < [buttonListInActionSheet count]; ++idxBtn) {
        UIButton *btn = [buttonListInActionSheet objectAtIndex:idxBtn];
        btn.tag = (100 + idxBtn);
    }
    

    当我点击按钮时,我可以通过

    获取行信息
    - (void)buttonTouched:(id)sender {
       UIButton *btn = (UIButton *)sender;
       NSInteger idxBtn = (btn.tag - 100);
    }
    

    【讨论】:

    • 感谢您的意见。我不太清楚如何使用标签。您能否详细说明一下标签以及如何使用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-06
    • 2011-01-22
    • 2011-12-23
    • 1970-01-01
    • 1970-01-01
    • 2014-07-15
    • 2012-06-08
    相关资源
    最近更新 更多