2015-10-15 43 views
0

我下面这个教程创建一个等级按钮 - https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson5.htmladdSubView - 添加一个UIView内的按钮添加相同的按钮它的SuperView以及

我通过拖放创建的故事板内的UIViewController内的UIView并且UIView由下面的类来控制。

class RatingControl: UIView { 

    required init(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder) 
     let button = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44)) 
     button.backgroundColor = UIColor.redColor() 
     button.addTarget(self, action: "ratingButtonTapped:", forControlEvents: .TouchDown) 
     addSubview(button) 
    } 

    override func intrinsicContentSize() -> CGSize { 
     return CGSize(width: 320, height: 44) 
    } 

    func ratingButtonTapped(button: UIButton) { 
     print("Button pressed ") 
    } 
} 

问题是,当我添加的UIButton,它示出了两个按钮,一个在它的位置在亲本的UIViewController(X:0,Y:0)除了UIView的内部的一个。我希望按钮仅在UIViewController中的UIView内显示。

我研究了防止它的方法,一种方法是在故事板中手动添加这些按钮,而不是在init中创建它们,但后来我很好奇它在教程中如何正常工作。我正在使用iOS 8.3。

截图:

enter image description here

回答

1

你必须有子类的UIViewControllers视图类也RatingControl也已添加视图它显示了两次,因为其中。请检查它,因为它的工作原理正确,如果ü只是把它添加到你需要

enter image description here

如果您已经添加了子类的ViewControllers查看以及你会得到这样的观点,这是按照您的方案

enter image description here

+0

你不介意阐述,我尽我所能理解你的说法,我相信这是正确的方向,以解决这一一步。在主Storyboard的UIViewController中,我拖放了一个UIView,将它的类设置为RatingControl,它扩展了UIView并添加了上述方法。 – sysuser

+0

我已经尝试了你粘贴的代码,它的工作原理是正确的,我的意思是你必须将ViewControllers视图子类化为RatingControl,在这种情况下,它会与超级视图一起添加到子视图 –

+1

请检查编辑后的答案,你会得到什么,还可以看看ViewControllers视图,它也被设置为Rating控制,这也是你在superView上获得按钮的原因。在第一张图片中,我添加了一个视图,我已将这个视图放在Storyboard上,只是它被分类到了RatingControl,并且它按照您的要求工作。你可以附上你的故事板图片 –

1

尝试,而不是

addSubview(button) 

这样的:

view.addSubview(button) 

它会将此按钮添加到您的viewController