ios - 尝试从 UIView 访问标签

标签 ios xcode swift

我创建了一个 .xib 文件,其中包含一堆标签,可与 SwipeView 一起使用。 。我的问题是我无法/不知道如何在加载 View 后访问和更改其文本:

let newView = NSBundle.mainBundle().loadNibNamed("SwipeHelperView", owner: self, options: nil)[0] as UIView

for (var subview) in newView.subviews
{           
    if (subview.isKindOfClass(UILabel) && subview.tag == 0)
    {
        subview.text = "asdaS" //ERROR: cannot assign 'text' in 'subview'
    }                
}

当场创建标签会更容易吗,如下所示:

var label = UILabel(frame: CGRectMake(0, 0, 200, 21))
label.center = CGPointMake(0, 0)
label.text = "some text"
newView.addSubview(label)

而不是尝试从“newView”UIView 访问它们?有“推荐”方式还是与偏好有关?

最佳答案

你应该转换它:

let newView = NSBundle.mainBundle().loadNibNamed("SwipeHelperView", owner: self, options: nil)[0] as UIView

for subview in newView.subviews as [UIView]
{           
    if subview.tag == 0
    {
        if let label = subview as? UILabel {
            label.text = "asdaS"
        }
    }                
}

如果您设置自定义标签(例如 333),您可以获得它:

if let label = newView.viewWithTag(333) as? UILabel {
    label.text = "TEST"
}

关于ios - 尝试从 UIView 访问标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26232170/

相关文章:

xcode - 从 Xcode 将图像推送到 Git Repo

Swift 3 - 检索字符串的特定部分

ios - 显示 Segue 未进入导航堆栈。 View Controller 上没有后退按钮,并且它是从底部而不是左侧向上滑动

ios - MKMapView 区域在 iOS7 中的方向更改后变得 splinter

html - 如何在 BakerFramework 报亭应用程序中添加状态栏而不在内容下方留出空间?

ios - 在 tableview 单元格中以编程方式从 Storyboard 中向下移动 UITextView

iOS 使用 vImage - 加速将 QCAR YUV 转换为 RGB

iphone - id 没有警告?

ios - 如何运行导致框架运行时错误的 iOS 应用程序 "code signature invalid"

ios - 部署目标是什么意思?