addSubView - 在UIView中添加一个按钮也为它的SuperView添加了相同的按钮

时间:2015-10-15 07:00:54

标签: ios swift uiview uiviewcontroller

我正在按照本教程创建评级按钮 - https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson5.html

我通过拖放在Storyboard内部的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时,除了UIView中的一个按钮之外,它还显示了两个按钮,其中一个位于其位置(x:0,y:0)的父UIViewController。我希望按钮只显示在UIViewController内部的UIView中。

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

截图:

enter image description here

2 个答案:

答案 0 :(得分:1)

你必须将UIViewControllers视图类子类化为RatingControl以及你添加的视图,因为它显示了两次。请检查它,因为如果你只将它添加到你需要的视图中它可以正常工作

enter image description here

如果您已将子类添加到ViewControllers视图中,那么您将获得此视图(根据您的方案)

enter image description here

答案 1 :(得分:1)

尝试代替

addSubview(button)

这样:

view.addSubview(button)

它会将此按钮添加到viewController