【问题标题】:How can i change the properties of a UIView so it can be casted to UILable or UIImageView?如何更改 UIView 的属性,使其可以转换为 UILable 或 UIImageView?
【发布时间】:2012-03-09 09:53:07
【问题描述】:

我想做的是从网络服务中读取一些内容,每个内容都有内容类型(文本、图像、按钮...)。 我必须在 UIView 中动态显示内容。所以我要做的是创建一个 IBoutlet UIView 并检查内容类型是否是文本我将此 uiview 转换为 UILable 并显示文本,如果内容类型是图像我将 UIView 转换为 UIImageView 等。 . 我需要在 xib 文件中处理相同的 UIView,那么如何将 UIView 的属性更改为 UILable 或 UIImageView。

谢谢

【问题讨论】:

    标签: iphone objective-c uiview uiimageview uilabel


    【解决方案1】:

    您不能将 UIView “更改”为不同的东西。
    我建议你在视图中动态添加子视图:

    UIView *newView = nil;
    switch (content type) {
        case 0: // text
            newView = [[UILabel alloc] init];
            ((UILabel*)newView).text = @"someText";
            [newView sizeToFit];
        case 1: // button
        {
            UIButton *btn = [UIButton buttonWithType:...];
            [btn setTititle:@"Ttile" forControlState:UIControlStateNormal]; // assign all needed properties
            ...
            newView = btn;
        }
        case 2:
        ....
    }
    newView.frame = ... // calculate Frame using previously created content (e.g. remember y offset and add bounds.size.height after every iteration)
    [self.view addSubView:newView];
    ....
    

    【讨论】:

    • 非常感谢,这正是我想要的。
    • 如果我尝试执行 newView=[[UILabel alloc]initWith...我无法将文本添加到 newView,因为 newView 是 UIView 而不是 UILabel...我的意思是我不能写 newView.text=@"someText";
    • 已编辑以显示两种将 var 引用为“真实”类型的方式
    猜你喜欢
    • 2013-01-31
    • 1970-01-01
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    • 2015-07-04
    • 1970-01-01
    • 1970-01-01
    • 2013-06-30
    相关资源
    最近更新 更多