簡體   English   中英

如何創建可以由多個UIVIewController共享/使用的UIView?

[英]How to create a UIView that can be shared/used by multiple UIVIewController?

我正在尋找以UIView的形式構建自定義錯誤消息。 我想為我的應用程序中的每個UIViewController使用此UIView 顯然,我不想為每個屏幕都重新創建它,因此我正在尋找“共享”它的最佳解決方案。

將其創建為UIViewController並以這種方式添加它會更好還是有更好的方法?

UIView實例只能在一個地方使用。 它們只能具有一個superview ,因此不能同時在多個視圖層次結構中使用。

如果更改superview視圖,則實際上將移動視圖。

我認為有兩種可能性:

  • 您可能希望始終在屏幕上顯示此錯誤消息。 在這種情況下,您應該創建一個專用的UIViewController,並始終將其顯示在屏幕上,
  • 或者您想顯示其他錯誤。 這樣,就可以為其中顯示錯誤的每個控制器創建UIView實例。

是的,請使用ViewController,它比簡單的視圖要好。 您的消息可能包含按鈕之類的操作。

為了避免過多的代碼重復,您可以使用mixin:

protocol ErrorDisplay {
    func display(_ error: Error)
}

extension ErrorDisplay where Self: UIViewController {
    func display(_ error: Error) {
        let viewController = ErrorViewController(error: error)
        // You could also add it as a child view controller rather than presenting it, 
        // if you want to add its view in the current hierarchy
        present(viewController, animated: true, completion: nil)
    }
}

並在希望顯示錯誤的每個視圖控制器中實現該協議。

extension LoginViewController : ErrorDisplay {}
extension SettingsViewController : ErrorDisplay {}
...

如果您希望當時始終在屏幕上顯示的視圖,可以使用window顯示視圖。

“窗口”是屏幕上顯示的所有視圖的根,“窗口”始終存在,因此一旦在窗口中添加視圖,該視圖就會一直存在於屏幕中。

只需使用以下代碼將視圖添加到窗口

let window = UIApplication.shared.keyWindow!
let v = UIView(frame: CGRect(x: window.frame.origin.x, y: window.frame.origin.y, width: window.frame.width, height: window.frame.height))
window.addSubview(v);

對於這個問題,我希望您創建一個UIView類,並且可以在viewController中重用它。 為此,請按照以下步驟操作,

1. Create a Xib of UIView and design it what ever you want.
2. Create a UIView class
3. Change the fileOwner of Your UIView XIB to the created UIView class
4.  Create an Outlet of ContentView in YourView.h
 @property (strong, nonatomic) IBOutlet UIView *contentView;
5. Add the following codes in YouView.m

 -(instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if(self)
    {
        [self customInit];
    }
    return self;
}

-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self)
    {
        [self customInit];
    }
    return  self;
}

-(void) customInit
{
    [[NSBundle mainBundle]loadNibNamed:@"View" owner:self options:nil];
    [self addSubview:self.contentView];
    self.contentView.frame = self.bounds;
}

6. Use this UIView in your ViewController what ever you want.

YourView *YourViewObj = [[YourView alloc] initWithFrame:CGRectMake(0, 0, 100,100)];
[self.view addSubview:YourViewObj];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM