如何从Swift中的另一个视图调用contentOffset?

时间:2016-07-07 10:10:44

标签: ios swift uiscrollview contentoffset

class oneViewController: UIViewController{
   let sv = UIScrollView();
   override func viewDidLoad() {
   super.viewDidLoad();

   sv.frame = CGRectMake(0, 100, screenWidth, screenHeight);
   sv.backgroundColor = UIColor.clearColor();
   sv.contentSize = CGSize(width: sv.frame.size.width*3 ,height: sv.frame.size.height);
   sv.delegate = self;
   scrollToContentOffsetX(screenWidth);
   self.view.addSubview(sv);
   }


  func scrollToContentOffsetX(offsetX:CGFloat) {

       sv.contentOffset.x = offsetX;
  }
}

我可以滚动UIScrollView,它正常工作。但是我从另一个View调用,它无效。

class anthorView: UIView{

    override init (frame : CGRect)
    {

    super.init(frame : frame)

      let btnForget = UIButton(frame: CGRectMake(screenWidth-155, txtPWD.frame.origin.y+txtPWD.frame.size.height+5, 70, 30));
      btnForget.setTitle("Forget", forState: UIControlState.Normal);
      btnForget.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal);
      btnForget.addTarget(self, action: #selector(btnForget_Click), forControlEvents: .TouchUpInside);
      btnForget.titleLabel!.font = UIFont.systemFontOfSize(14);
      btnForget.backgroundColor = UIColor.clearColor();
      self.addSubview(btnForget);
    }

func btnForget_Click(sender: AnyObject) {

    oneViewController().scrollToContentOffsetX(0);

  }
} 

我有断点,两者都去了func scrollToContentOffsetX(offsetX:CGFloat)。 谁可以帮助我,为我的英语而努力

1 个答案:

答案 0 :(得分:3)

@ AminNegm-Awad指出的代码中的问题:在Error using AdaptBinarize2>parseInputs (line 371) The value of 'meanWindow' is invalid. It must satisfy the function: isint. Error in AdaptBinarize2 (line 67) p = parseInputs(I, algorithm, varargin{:}); %check all the name-value pairs and datatypes. local function. 中,您创建了btnForget_Click的全新实例,该实例永远不会出现在屏幕上,并且与现有的oneViewController没有任何关联。您需要在oneViewController实例中指向现有的oneViewController实例。通常与控制器“对话”的方式是协议委托。亲自阅读;在这里,我将提供另一种封闭解决方案。无论如何,您需要在anthorView中指向anthorView实例(允许将其声明为anthorViewInstance属性)。以下是您需要添加到课程中的更改

类anthorView:

oneViewController

类oneViewController:

var offsetClosure: (CGFloat -> ())?

func btnForget_Click(sender: AnyObject) {
    // delete previous implementation
    offsetClosure?(0)
}

此外,还有本地案例可以在您的情况下执行此解决方案。您可以直接从视图控制器设置var anthorViewInstance: anthorView! override func viewDidLoad() { super.viewDidLoad() // some your code... // next line is initialization of anthorView, do it in other place if you wish anthorViewInstance = anthorView(frame: CGRectZero) anthorViewInstance.offsetClosure = { [weak self] offsetX in self?.scrollToContentOffsetX(offsetX) } } 的按钮操作。为此,请在anthorView

中将按钮声明为属性

类anthorView:

anthorView

类oneViewController:

var btnForget: UIButton!

super.init(frame : frame) {
    btnForget = UIButton(frame: CGRectMake(screenWidth-155, txtPWD.frame.origin.y+txtPWD.frame.size.height+5, 70, 30))

    // ... other init code

    // remove btnForget.addTarget line
}

// move btnForget_Click method to view controller