【问题标题】:Copying UIButtons frame gives wrong position复制 UIButtons 框架给出了错误的位置
【发布时间】:2017-11-24 10:53:08
【问题描述】:

我想在 UIButton 上创建另一个 UIView / UIButton,所以我得到了它的框架并在另一个 UIView 的声明中使用它,但它创建如下截图(带有蓝色视图)。顺便说一句,按钮是在情节提要上创建的。

我正在使用 Xcode 9.1 和 iOS 11.1

- (void)viewDidLoad {

    UIView *picker = [[UIView alloc] initWithFrame:_mButton.frame];
    picker.backgroundColor=[UIColor blueColor];
    [self.view addSubview: picker];
}

Screenshot 1 Screnshot 2

【问题讨论】:

    标签: ios objective-c uiview uibutton frame


    【解决方案1】:

    我猜viewDidLoad 中没有计算正确的帧。您可以尝试将picker 设为属性并在viewDidLayoutSubviews 中调整其框架

    @property (strong, nonatomic) UIView *picker;
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        self.picker = [[UIView alloc] initWithFrame:_mButton.frame];
        self.picker.backgroundColor=[UIColor blueColor];
        [self.view addSubview: self.picker];
    }
    
    - (void)viewDidLayoutSubviews {
        self.picker.frame = _mButton.frame;
        [super viewDidLayoutSubviews];
    }
    

    但是如果你有这种可能性,当然使用故事板和自动布局可能是最好的解决方案。

    【讨论】:

    • 您是否使用边界来设置框架?如果你这样做: self.picker.frame = _mButton.frame 框架可能不正确,因为按钮位置不在 x=0 和 y= 0
    • 我可以在 ViewWillAppear 上调用它吗?我认为这将是解决方案,但它也不起作用。
    • 不,我使用的是 _mButton.frame
    • 当我使用边界时,它出现在左上角。
    • 太棒了。这是因为按钮的框架与其父视图有关。所以 x 和 y 将有不同的值。当您希望此选择器覆盖您的按钮时,您需要 x 和 y 都为零。这可以通过使用边界而不是框架来获得。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-22
    相关资源
    最近更新 更多