Vuko Vuko -4 years ago 109
iOS Question

Setting ContentOffset using buttons

I have made a .xib file with couple of buttons and attached it to the inputAccessoryView. I made this section scrollable with scrollView, however I have to add additional functionality using buttons (arrows). Clicking forward arrow it should go to the end and back arrow would take as to the original position.

first position - start
second position - end

I made whole ScrollView in UI without any code. It works well, those buttons are on top of this view.I was thinking of using IBAction of these buttons and changing ContentOffSet. I am struggling with implementation. I will be grateful for some tips.

Class for implementation:

#import "KCSearchInputAccessoryView.h"

@implementation KCSearchInputAccessoryView

+ (KCSearchInputAccessoryView *)viewFromNib {
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
return [[bundle loadNibNamed:NSStringFromClass([self class]) owner:nil options:nil] lastObject];
}

- (IBAction)backBtnTapped:(id)sender {

}

- (IBAction)forwardBtnTapped:(id)sender {

}

@end

Answer Source

You can do it with changing ContentOffset, but...

Assuming you have references to the buttons, a better approach may be using func scrollRectToVisible(_ rect: CGRect, animated: Bool)

IBAction func rightButton(sender: AnyObject) {
    self.theScrollView.scrollRectToVisible(postsButton.frame, animated: true)
}

IBAction func leftButton(sender: AnyObject) {
    self.theScrollView.scrollRectToVisible(chatsButton.frame, animated: true)
}

This would also "slide" the buttons across.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download