简体   繁体   English

addSubView-在UIView中添加按钮也会为其SuperView添加相同的按钮

[英]addSubView - adding a button inside a UIView adds the same button for it's SuperView as well

I am following this tutorial to create a rating button - https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson5.html 我正在按照本教程创建评分按钮-https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson5.html

I created a UIView inside a UIViewController inside the Storyboard by drag and drop and that UIView is controlled by the below class. 我通过拖放在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 👍")
    }
}

The problem is when I add the UIButton, it's showing two buttons, one in it's parent UIViewController at location (x:0, y:0) in addition to the one inside the UIView. 问题是当我添加UIButton时,它显示了两个按钮,一个位于UIView内部的按钮,另一个位于位置(x:0,y:0)的父UIViewController中。 I want the button to be showing only inside the UIView inside the UIViewController. 我希望按钮仅在UIViewController内的UIView内显示。

I researched ways to prevent it, one way is to add these buttons manually in the storyboard instead of creating them in the init, but then I am curious how it works fine in the tutorial. 我研究了防止这种情况的方法,一种方法是在情节提要中手动添加这些按钮,而不是在init中创建它们,但是我很好奇它在本教程中的工作方式。 I am using iOS 8.3. 我正在使用iOS 8.3。

Screenshot: 屏幕截图:

在此处输入图片说明

you must have subclassed the UIViewControllers view class also to RatingControl and also the view that you have added because of which it is showing it twice. 您还必须将UIViewControllers视图类也子类化为RatingControl以及添加的视图,因此该视图将显示两次。 Kindly check it because it works proper if u only add it to the view you need 请检查一下,因为如果您仅将其添加到所需的视图中,它将正常工作

在此处输入图片说明

If you have added the subclass to the ViewControllers view as well you would get this , which is as per your scenario 如果您也已将子类添加到ViewControllers视图,则将获得此效果,这取决于您的方案

在此处输入图片说明

try instead of 尝试代替

addSubview(button)

this: 这个:

view.addSubview(button)

it will add this button to your viewController 它将添加此按钮到您的viewController

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM