Xcode Swift - 修改子视图属性

时间:2015-02-05 08:29:31

标签: ios xcode swift

我正在使用此功能创建一些导航按钮。

func create(size:CGFloat, y:CGFloat, button:Dictionary<String, String>) -> UIButton {
    // setup size variables
    let width = size;

    var height = size;
    if button["position"] == "top" || button["position"] == "bottom" {
        height = size+1;
    }

    var marginTop:CGFloat = 1
    if button["position"] == "top" {
        marginTop = 0
    }

    // create button
    let btn = UIButton(frame: CGRectMake(UIScreen.mainScreen().bounds.width-width, y*size, width, height))

    // background image
    let bgImage = UIImageView(frame: CGRectMake(0, marginTop, width, height-2))
    bgImage.image = UIImage(named: "nav-bg.png")

    // background image active
    var bgImageActive = UIImageView(frame: CGRectMake(0, marginTop, width, height-2))
    bgImageActive.image = UIImage(named: button["bg-active"]!)
    bgImageActive.hidden = true
    bgImageActive.alpha = 0

    // button icon
    let iconImage = UIImageView(frame: CGRectMake(0, marginTop, width, height-2))
    iconImage.image = UIImage(named: button["icon"]!)

    // button label
    let label = UILabel(frame: CGRectMake(10, height-35, width-20, 30))
    label.text = button["name"]!
    label.textColor = UIColor.whiteColor()
    label.font = UIFont(name: "HelveticaNeue-Bold", size: 10)
    label.textAlignment = NSTextAlignment.Center
    label.numberOfLines = 2

    // add subviews
    btn.addSubview(bgImage)
    btn.addSubview(bgImageActive)
    btn.addSubview(iconImage)
    btn.addSubview(label)

    return btn
}

var btn = create(navBtnSize, y: CGFloat(i), button: navButtonSettings[i])
btn.addTarget(self, action: "navBtnTapped:", forControlEvents: UIControlEvents.TouchUpInside)

func navBtnTapped(sender:UIButton) {
    // change button subview properties
}

点击按钮时如何设置“bgImageActive”子视图不被隐藏?由于按钮是从函数创建的,因此无法按名称调用ImageView。

我试过了:

sender.subviews[1].hidden = false

但这会导致错误:

'AnyObject' does not have a member named hidden.

我无法弄清楚如何修改子视图属性。

我想我也可以尝试标记UIImageView并调用:

bgImageActive.tag = 1
~
sender.viewWithTag(1).hidden = false

但这也不起作用。

任何帮助都将不胜感激。

干杯。

1 个答案:

答案 0 :(得分:5)

尝试

(sender.subviews[1] as UIImageView).hidden = false

问题是,子视图数组存储了AnyObjects,而Anyobject没有隐藏属性,所以你必须按顺序拥有该属性。